【问题标题】:jQuery ajax returned data: json and html mix?jQuery ajax 返回数据:json 和 html 混合?
【发布时间】:2014-01-11 15:49:30
【问题描述】:

我有这个 ajax 请求从我的服务器获取数据,默认情况下dataType 始终是html。但是有时候它会从服务器返回json,所以我想检查返回的数据是不是html然后执行A else执行B。可以吗?

我的 jquery,

 $.ajax({
     type: "GET",
     dataType: "html",
     url: request_url,
     context: $('#meat'),
     async: true,
     beforeSend: function () {},
     success: function (returndata, status, jqXHR) {
         if ($.parseJSON(returndata) === false) A;
         else B.
     }
 });

当返回的数据为html时出现此错误,

SyntaxError: JSON.parse: 意外字符

那么我怎样才能让这段代码通用

【问题讨论】:

  • 确保您将数组解析为 json_encode() ?
  • 对于 json 数据是。但如果返回的数据是html,我不使用json_encode
  • 你可以试试这个:dataType: "json" || "html",,你可以尝试使用typeof()方法返回数据,如果是object,则将其处理为json。

标签: javascript ajax json jquery


【解决方案1】:

我不确定是否有更好的方法,但你可以尝试...抓住

$.ajax({
      type:       "GET",
      url:        request_url,
      context:    $('#meat'),
      async:      true,
      beforeSend: function() {
      },
      success: function (returndata, status, jqXHR) {
        var parsed;
        try
        {
            parsed = $.parseJSON(returndata);
            // Execute B
        }
        catch(e)
        {
           // treat as html then
           // do parsing here
           parsed = returnData;
           // Execute A
        }
      }

});

【讨论】:

    【解决方案2】:

    基本上,您的代码完全是错误的 - 如果返回类型可能以不一致的方式变化,您的服务器端 API 就违反了所有可预测性原则。您的代码永远不必猜测返回数据的类型。

    话虽如此,如果您不想修复它,a simple try/catch 将有助于解决不稳定行为。即。

    try {
        if ($.parseJSON(returndata) === false) A;
    } catch(e) {
        // Treat as HTML here.
    }
    

    它并不漂亮,但这就是你拥有一个一开始并不漂亮的不可预测的 API。

    【讨论】:

    • 谢谢。但是当我传入一个 json 数据时,这条线 if ($.parseJSON(returndata) === false) 没有做任何事情。
    • 我只是从您的代码中复制了该部分 - 我的回答是关于规避错误,而不是关于您可能遇到或可能没有的其他问题;)
    【解决方案3】:

    可能你需要这样处理

    try{
    var response=jQuery.parseJSON('response from server');
    if(typeof response =='object')
     {
        //control would reach this point if the data is returned as json
     }
     else
     {
        //control would reach this point if data is plain text  
         if(response ===false)
         {
             //the response was a string "false", parseJSON will convert it to boolean false
         }
         else
         {
              //the response was something else
         }
     }
    }
    catch(exp){
        //controls reaches here, if the data is html
    }
    

    由于您还需要检查 html 数据,因此您可能需要注意这一点,

    如果 parseJSON 可能会处理 JSON 值以外的其他内容(即 HTML),则可能还需要使用 try / catch 处理异常

    REF:How can I check if a value is a json object?

    编辑:编辑以使代码更精确地解决问题

    【讨论】:

    • 行不通,他的整个核心问题是parseJSON 抛出一个错误,所以你的大部分代码在问题情况下都是“无法访问”的。
    • @NielsKeurentjes:这就是我添加一条消息(斜体)的原因,说 parseJSON 需要包含在 try catch 块中以处理 html 数据的异常被退回。
    • @NielsKeurentjes:我已经编辑了答案,我想现在可以了
    猜你喜欢
    • 1970-01-01
    • 2015-08-06
    • 1970-01-01
    • 2011-09-16
    • 2016-01-10
    • 2012-06-24
    • 1970-01-01
    • 1970-01-01
    • 2021-11-30
    相关资源
    最近更新 更多