dataType'application / json'与'json' [英] dataType 'application/json' vs. 'json'

查看:221
本文介绍了dataType'application / json'与'json'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

$ .ajax - dataType

我正在使用jQuery 1.8.2,对于某些人来说原因'application / json'不起作用,但'json'作为 dataType 到标准 jquery ajax 调用。这是一个小故障吗?与版本相关的区别?或两者之间是否存在既定差异?

I am using jQuery 1.8.2, and for some reason 'application/json' does not work, but 'json' works as dataType to a standard jquery ajax call. Is this a glitch? A version related difference? or is there an established difference between the two?

$(document).ready(function() {
    $.ajax({
        type : "POST",
        url : '<c:url value="/url.htm" >',
        //dataType : "application/json", <-- does not work
        dataType: 'json' // <-- works
        success : function(data) {
            // do something          
        },
        error : function(data) {
            // do something else
        }
    });
});


推荐答案

dataType 接受json,这意味着请求需要 json 响应。

dataType takes json, it means the request expects a json response.

contentType 接受 application / json ,这意味着请求发送 json 数据

contentType takes application/json, it means the request is sending json data

您可以在请求中发送和期望json,例如

You can send as well as expect json in a request e.g.

$.ajax({
    type : "POST",
    url : url,
    contentType : "application/json", 
    dataType: 'json',
    data: JSON.stringify({some: 'data'}),
    success : function(data) {
        // do something          
    },
    error : function(data) {
        // do something else
    }
});

这里你发送json并期待xml

here you're sending json and expecting xml

$.ajax({
    type : "POST",
    url : url,
    contentType : "application/json", 
    dataType: 'xml',
    data: JSON.stringify({xmlfile: 'file.xml'}),
    success : function(data) {
        // do something          
    },
    error : function(data) {
        // do something else
    }
});

在这里你发送 x-www-form-urlencoded (jQuery自动为你设置),并期待json回来

and here you're sending x-www-form-urlencoded(jQuery automatically sets this for you), and expect json back

$.ajax({
    type : "POST",
    url : url,
    dataType: 'json',
    data: {id: '1'},
    success : function(data) {
        // do something          
    },
    error : function(data) {
        // do something else
    }
});

contentType设置 ContentType HTTP请求标头,告诉服务器该请求的主体是给定类型的。

dataType设置 Accept 标头告诉服务器这是一种类型我们想要的回复例如

contentType sets the ContentType HTTP request header, telling the server that the body of this request is of the given type.
dataType sets the Accept header to tell the server that this is the type of response we want e.g.

Accept:application/json, text/javascript, */*; q=0.01

但无论服务器发送什么类型的响应,jQuery仍会尝试将其解析为您在dataType字段中设置的任何类型。

but regardless of what type of response the server sends jQuery will still attempt to parse it as whatever type you set in the dataType field.

这篇关于dataType'application / json'与'json'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆