问题描述
POST请求中的内容类型和数据类型是什么?假设我有这个:
What is content-type and datatype in a POST request? Suppose I have this:
$.ajax({
type : "POST",
url : /v1/user,
datatype : "application/json",
contentType: "text/plain",
success : function() {
},
error : function(error) {
},
contentType
是我们发送的吗?那么我们在上面的示例中发送的是JSON,而我们接收的是纯文本?我不太了解.
Is contentType
what we send? So what we send in the example above is JSON and what we receive is plain text? I don't really understand.
推荐答案
contentType
是您要发送的数据类型,因此application/json; charset=utf-8
是常见的数据,application/x-www-form-urlencoded; charset=UTF-8
也是如此,这是默认设置.
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
是您希望从服务器返回的内容:json
,html
,text
等.jQuery将使用它来确定如何填充成功函数的参数.
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"}
并期待回来:
{"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
},
});
再来一次-如果您要发布:
One more - if you want to post:
name=John&age=34
然后不要stringify
数据,然后执行以下操作:
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请求中的内容类型和数据类型是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!