Answers:
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
},
});
[HttpPost]public JsonResult user(Person postedPerson) { /* Save postedPerson to DB */ return Json(new { success = true }); }
$.ajax({ dataType : "html", ...
而不是$.ajax({ datatype : "html",...
单词Type中的大写T 来代替 。检查jQuery API
requestContentType
和responseDataType
,但在现实中,一旦你已经做了几次,你懂的API,你将不会被混淆不足以使额外的输入值得的。
从jQuery文档-http://api.jquery.com/jQuery.ajax/
contentType将数据发送到服务器时,请使用此内容类型。
dataType您期望从服务器返回的数据类型。如果未指定任何内容,则jQuery将尝试根据响应的MIME类型进行推断
“文本”:纯文本字符串。
因此,您希望contentType为,application/json
而dataType为text
:
$.ajax({
type : "POST",
url : /v1/user,
dataType : "text",
contentType: "application/json",
data : dataAttribute,
success : function() {
},
error : function(error) {
}
});
参见http://api.jquery.com/jQuery.ajax/,其中提到了数据类型和contentType。
它们都在对服务器的请求中使用,因此服务器知道要接收/发送什么样的数据。