What is content-type and datatype in an AJAX request?

https://api.jquery.com/jquery.ajax/

What is content-type and datatype in an AJAX request?

contentType is the type of data you're sending, so application/json; charset=utf-8 is a common one, as is application/x-www-form-urlencoded; charset=UTF-8, which is the default.

dataType is what you're expecting back from the server: json, html, text, etc. jQuery will use this to figure out how to populate the success function's parameter.

If you're posting something like:

{"name":"John Doe"}

and expecting back:

{"success":true}

Then you should have:

var data = {"name":"John Doe"}
$.ajax({
    dataType : "json",
    contentType: "application/json; charset=utf-8",
    data : JSON.stringify(data),
    success : function(result) {
        alert(result.success); // result is an object which is created from the returned JSON
    },
});

If you're expecting the following:

<div>SUCCESS!!!</div>

Then you should do:

var data = {"name":"John Doe"}
$.ajax({
    dataType : "html",
    contentType: "application/json; charset=utf-8",
    data : JSON.stringify(data),
    success : function(result) {
        jQuery("#someContainer").html(result); // result is the HTML text
    },
});

One more - if you want to post:

name=John&age=34

Then don't stringify the data, and do:

var data = {"name":"John", "age": 34}
$.ajax({
    dataType : "html",
    contentType: "application/x-www-form-urlencoded; charset=UTF-8", // this is the default value, so it's optional
    data : data,
    success : function(result) {
        jQuery("#someContainer").html(result); // result is the HTML text
    },
});

$.ajax - dataType

  • contentType is the header sent to the server, specifying a particular format.
    • Example: I'm sending json or XML
  • dataType is you telling jQuery what kind of response to expect.
    • Expecting JSON, or XML, or HTML, etc....the default it for jQuery to try and figure it out.

The $.ajax() documentation has full descriptions of these as well.

In your particular case, the first is asking for the response to be in utf-8, the second doesn't care. Also the first is treating the response as a javascript object, the second is going to treat it as a string.

So the first would be:

success: function(data) {
  //get data, e.g. data.title;
}

The second:

success: function(data) {
  alert("Here's lots of data, just a string: " + data);
}
原文地址:https://www.cnblogs.com/chucklu/p/11649980.html