码迷,mamicode.com
首页 > Web开发 > 详细

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

时间:2019-10-10 20:02:31      阅读:89      评论:0      收藏:0      [点我收藏+]

标签:and   bre   ajax   target   return   get   javascrip   type   HERE   

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);
}

 

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

标签:and   bre   ajax   target   return   get   javascrip   type   HERE   

原文地址:https://www.cnblogs.com/chucklu/p/11649980.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!