AJAX请求中的content-type和datatype是什么?

use*_*697 168 jquery

POST请求中的content-type和datatype是什么?假设我有这个:

$.ajax({
    type : "POST",
    url : /v1/user,
    datatype : "application/json",
    contentType: "text/plain",
    success : function() {

    },
    error : function(error) {

    },
Run Code Online (Sandbox Code Playgroud)

contentType我们送的吗?那么我们在上面的例子中发送的是JSON,我们收到的是纯文本?我真的不明白.

Joe*_*nos 277

contentType是您要发送的数据类型,因此application/json; charset=utf-8是常见的数据application/x-www-form-urlencoded; charset=UTF-8,这是默认值.

dataType是你从服务器期待什么时候回来:json,html,text等jQuery将使用这个弄清楚如何填充成功函数的参数.

如果您发布的内容如下:

{"name":"John Doe"}
Run Code Online (Sandbox Code Playgroud)

并期待回来:

{"success":true}
Run Code Online (Sandbox Code Playgroud)

那你应该有:

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
    },
});
Run Code Online (Sandbox Code Playgroud)

如果您期望以下内容:

<div>SUCCESS!!!</div>
Run Code Online (Sandbox Code Playgroud)

然后你应该这样做:

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
    },
});
Run Code Online (Sandbox Code Playgroud)

还有一个 - 如果你想发布:

name=John&age=34
Run Code Online (Sandbox Code Playgroud)

然后不要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
    },
});
Run Code Online (Sandbox Code Playgroud)

  • 这只是一个普通的对象 - 它是由服务器决定制作的.Web服务器可以发送任何感觉 - HTML,文本,或者在这种情况下,JSON对象具有名为"success"且值为true的单个属性.我无法猜测你的API框架是什么,但是在ASP.NET MVC的C#中它会像`[HttpPost] public JsonResult用户(Person postedPerson){/*将postedPerson保存到DB*/返回Json(new) {success = true}); }` (2认同)
  • 注意你应该使用 `$.ajax({ dataType : "html", ... ` 而不是 `$.ajax({ datatype : "html",... ` 所以单词 Type 中的大写 T 很重要。检查[jQuery API](http://api.jquery.com/jquery.Ajax/) (2认同)

Ric*_*ton 30

来自jQuery文档 - http://api.jquery.com/jQuery.ajax/

contentType将数据发送到服务器时,请使用此内容类型.

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) {

    }
});
Run Code Online (Sandbox Code Playgroud)

  • 这就是我喜欢的东西...得到代表陈述明显的...> _ < (3认同)