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