jQuery的阿贾克斯返回" parsererror"尽管JSON是有效的,收益code是201 [英] jQuery Ajax returns "parsererror" despite JSON is valid and return code is 201

查看:159
本文介绍了jQuery的阿贾克斯返回" parsererror"尽管JSON是有效的,收益code是201的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将查询发送到服务器,作为回报,等待一个JSON对象:

I'm sending a query to a server and awaiting a JSON object in return:

var a = $.ajax(
{
    type: "POST",
    data: post_data,
    timeout: 5000,
    url: url,
    beforeSend: function (xhr)
    {
        xhr.setRequestHeader("Content-Type", "application/json"); 
    }
})
.success (function (data, status, jqxhr)
{       
    onSuccess();
})
.error (function(x, status, jqxhr) 
{   
    onError_(x);
});

这完美的作品,我收到了预期的JSON的回报:

That works perfectly, I'm getting the expected JSON in return:

{"readyState":4,"responseText":"","status":201,"statusText":"Created"}

但不是的onSuccess(),但的onError _()被调用和状态设置为parsererror尽管返回的是一个有效的JSON(我曾与各种工具,如的这个)和JSON元素,即使状态为 201 它根据的这个页面重新presents积极的状态code:

But not onSuccess() but onError_() gets called and status is set to 'parsererror' despite the return is a valid JSON (I've tested it with various tools like this) and even the status of the JSON element is 201 which according to this page represents a positive status code:

10.2.2 201创建

请求已经完成,并产生了一个新的资源被创造[...]

The request has been fulfilled and resulted in a new resource being created [...]

有没有可能,那jQuery的阿贾克斯跨$ P $点的201地位,作为一个失败?

Is it possible, that jQuery's Ajax interprets the 201 status as a failure?

更新:

还加入数据类型:JSON,来我的要求并没有改变的情况。 jQuery的文档阿贾克斯()表示,

Also adding dataType: "json", to my request doesnt change the situation. The jQuery documentation for .ajax() says

的dataType (默认:智能猜测(XML,JSON,脚本或HTML))

dataType (default: Intelligent Guess (xml, json, script, or html))

所以,当我实现它,我认为jQuery的不会这么愚蠢导致错误,因为它不承认JSON和看来我是对的,因为错误是一样的。

So when I implemented it I thought jQuery wouldn't be so dumb to cause errors because it doesn't recognize JSON and it seems that I was right because the error remains the same.

更新:

有关此问题的常见的修复似乎是,加入数据类型:JSON的AJAX调用,但是这对我没有工作,所以我做了一个丑陋,但工作解决方法:

The common fix for this problem seems to be, adding dataType: "json" to the ajax call, however this didn't work for me, so I did an ugly but working workaround:

.error (function(x, status, jqxhr) 
{
    if (x.status == 201) /* jQuery thinks, Status 201 means error, but it doesnt so we have to work around it here */
    {
        // handle success
        return;
    }

    // handle errors
}

不管怎样,我会在适当的修复仍有兴趣

Anyway, I'd be still interested in a proper fix

推荐答案

注意:responseText的等于,这是不是一个有效的JSON。它应该是null或{}

Be careful: ResponseText is equal to "" and that is not a valid json. It should be null or "{}"

这篇关于jQuery的阿贾克斯返回" parsererror"尽管JSON是有效的,收益code是201的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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