【问题标题】:Why does $.ajax call for json data trigger the error callback when http status code is "200 OK"?为什么http状态码为“200 OK”时$.ajax调用json数据会触发错误回调?
【发布时间】:2023-03-12 21:50:01
【问题描述】:

我有以下 ajax 请求:

        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 即。请求没问题。这是为什么呢?

【问题讨论】:

    标签: jquery ajax json error-handling http-status-codes


    【解决方案1】:

    您的回调是否返回带有Content-type: application/json 的页面?如果不是,那很可能是原因。

    【讨论】:

    • 我已经测试过了,似乎没关系。它在有和没有内容类型声明的情况下都有效(当它有效时)。
    • hmmm 也许那是原型库而不是 jquery
    【解决方案2】:

    问题可能是url返回的json数据格式错误。当服务器实际返回某些东西时,http 状态码是 200。但这并不意味着数据是正确的 json。检查返回的字符串化 json 数据格式是否正确。

    我正在回答我自己的猜测,因为我学到了很多东西。我没有在我的 json 数据中转义 "-quote 字符。这导致了非常奇怪的行为。幸运的是,双引号字符几乎是唯一需要从通过 JSON 传递的数据中转义的字符。(有关此问题的更多信息: Where can I find a list of escape characters required for my JSON ajax return type?)

    【讨论】:

      【解决方案3】:

      我使用 file: urls 进行了很多测试,而不是使用 Web 服务器。我的 JSON 代码总是有错误的 MIME 类型。为了解决这个问题,我使用以下代码:

      $(document).ready(
          function (){
      
              myData = {};
              $.ajax({
                  type: "GET",
                  // url: "json.php?fn=jsonData.json",        // with Apache
                  url: "jsonData.json",                       // As a file:/// URL
                  contentType: "application/json; charset=utf-8",
                  data: myData,
                  beforeSend: function(x) {
                      if(x && x.overrideMimeType) {
                          x.overrideMimeType("application/json; charset=UTF-8");
                      }
                  },
                  dataType: "json",
      
                  success: function(returnData){
                       $("#jsonData").html("Success:"+returnData.tag);
                  },
                  error: function(returnData) {
                       $("#jsonData").html("Error:"+returnData.tag);
                  }
              });
          }
      );
      

      这将强制 MIME 类型对 JSON 数据正确。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-03-24
        • 2013-04-20
        • 1970-01-01
        • 1970-01-01
        • 2018-05-05
        • 2011-10-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多