为什么当http状态代码为“200 OK”时,$ .ajax调用json数据会触发错误回调? [英] Why does $.ajax call for json data trigger the error callback when http status code is "200 OK"?

查看:184
本文介绍了为什么当http状态代码为“200 OK”时,$ .ajax调用json数据会触发错误回调?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下ajax请求:

I have the following ajax request:

        jQuery.ajax({
            async: true,
            type: "GET",
            url: url,
            data: data,
            dataType: "json",
            success: function(results){
                currentData = results;
            },
            error: function(xhr, ajaxOptions, thrownError){
                if (xhr.status == 200) {
                    console.debug("Error code 200");
                }
                else {
                    currentData = {};
                    displayAjaxError(xhr.status);
                }
            }
        });

由于某种原因,错误回调被称为事件,尽管HTTP状态代码为200 ie。请求可以。为什么是这样?

For some reason the error callback is called event though the http status code is 200 ie. the request is OK. Why is this?

推荐答案

问题可能是从url返回的json数据格式错误。当服务器实际返回某些东西时,http状态码为200.但是并不意味着数据是正确的json。检查返回的有条纹的json数据是否正确形成。

The problem might be that the json data returned from the url is malformed. When the server actually returns something, the http status code is 200. But that doesn't mean that the data is proper json. Check that the stringified json data returned is correctly formed.

我正在回答我自己的访问,因为我很难了解到这一点。我没有在我的json数据中逃脱一个-quote角色,这导致了非常奇怪的行为,幸运的是,双引号字符几乎是需要从通过JSON传递的数据中转义的唯一字符(更多关于此问题: 我在哪里可以找到我的JSON ajax返回类型所需的转义字符列表?

I'm answering my own guestion because I learned this the hard way. I hadn't escaped a "-quote character in my json data. This resulted in very odd behaviour. Luckily the double quote character is pretty much the only character that needs to be escaped from data delivered via JSON. (More on this issue: Where can I find a list of escape characters required for my JSON ajax return type?)

这篇关于为什么当http状态代码为“200 OK”时,$ .ajax调用json数据会触发错误回调?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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