【问题标题】:jQuery ajax call returns empty error if the content is empty如果内容为空,jQuery ajax 调用返回空错误
【发布时间】:2013-08-14 12:05:08
【问题描述】:

我每次在res.reply = 2 时调用getResult() 函数,但也有res 为空的情况。当返回值为空时,调用console.log("error")。这适用于旧版本的 jQuery Mobile。现在版本是1.3.2

function getResult()
{
    request = $.ajax({
        type: "POST",
        url: url,
        dataType: "json",
        data: {
            ....
        },
        error: function() {         
            console.log("error");
        },
        success: function(res) {
            if(res.reply=='2') {
                getResult();
            }         
        }
    });
}

【问题讨论】:

  • 期待 jQuery 1.3.2 的帮助有点……乐观。为什么不使用当前版本?
  • 点击error 处理程序并不一定意味着响应为空 - 它通常意味着由于服务器上的错误而无法检索响应。检查 Firebug 中的网络流量和您的服务器日志是否有错误。
  • 您收到什么错误..您可以通过error : function (xhr,err){ console.log(xhr);console.log(err); }查看
  • 因为是最新版本jquerymobile.com
  • console.log(xhr);console.log(err);返回 Object { readyState=4, status=200, statusText="OK"} search...mbers=1 (line 136) parsererror

标签: jquery jquery-mobile


【解决方案1】:
dataType: "json"

意思是:给我json,没有别的。空字符串不是json,所以接收到空字符串意味着它没有成功...

request = $.ajax({
    type: "POST",
    url: url,
    data: {
        ....
    },
    error: function() {         
        console.log("error");
    },
    success: function(res) {
        var response = jQuery.parseJSON(res);
        if(typeof response == 'object'){
            if(response.reply == '2') {
                getResult();
            }  
        } else {
              //response is empty 
        }
    }
});

【讨论】:

    【解决方案2】:

    看起来您通常确实需要 JSON 响应,所以我不会将您的 dataType 更改为“文本”,而是让服务器返回有效的 JSON 响应,即使响应为空,例如“{}”而不是“”。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-26
      • 2017-08-20
      • 1970-01-01
      相关资源
      最近更新 更多