POST请求中的内容类型和数据类型是什么?假设我有这个:
$.ajax({
type : "POST",
url : /v1/user,
datatype : "application/json",
contentType: "text/plain",
success : function() {
},
error : function(error) {
},
contentType是我们发送的内容吗?所以我们在上面的例子中发送的是JSON,而我们接收的是纯文本?我不太明白。
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
然后不要对数据进行字符串化,并执行:
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
},
});
来自jQuery文档- http://api.jquery.com/jQuery.ajax/
当向服务器发送数据时,使用该内容类型。
dataType您期望从服务器返回的数据类型。如果没有指定,jQuery将尝试基于
响应的MIME类型
text:纯文本字符串。
所以你想让contentType为application/json, dataType为text:
$.ajax({
type : "POST",
url : /v1/user,
dataType : "text",
contentType: "application/json",
data : dataAttribute,
success : function() {
},
error : function(error) {
}
});
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
然后不要对数据进行字符串化,并执行:
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
},
});