contentType
是您发送的数据类型,所以application/json; charset=utf-8
是一种常见的,因为application/x-www-form-urlencoded; charset=UTF-8
,这是默认值。
dataType
是您期望从服务器返回的内容:json
, html
, text
等等。jQuery 将使用它来确定如何填充成功函数的参数。
如果您发布类似以下内容:
{"name":"John Doe"}
并期待回来:
{"success":true}
那么你应该有:
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
},
});
如果您期待以下内容:
<div>SUCCESS!!!</div>
那么你应该这样做:
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
},
});
再发一篇 - 如果您想发帖:
name=John&age=34
那么就不要stringify
数据,并执行以下操作:
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
},
});