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

查看:25
本文介绍了为什么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,即.请求没问题.这是为什么?

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天全站免登陆