如果内容为空,jQuery ajax 调用返回空错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18231285/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 21:14:28  来源:igfitidea点击:

jQuery ajax call returns empty error if the content is empty

jqueryjquery-mobile

提问by user2632980

I call the getResult()function everytime when res.reply = 2, but there are cases that resis empty. When the returned value is empty console.log("error")is invoked. This works in older versions of jQuery Mobile. Now the version is 1.3.2.

getResult()每次 whenres.reply = 2都调用该函数,但有些情况下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();
            }         
        }
    });
}

回答by Mr.Manhattan

dataType: "json"

means: give me json, nothing else. an empty string is not json, so recieving an empty string means that it wasn't a success...

意思是:给我 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 
        }
    }
});

回答by Hymanocnr

Looks like normally you do want a JSON response, so I wouldn't change your dataType to "text", instead I would get the server to return a valid JSON response even when the response is empty e.g. "{}" instead of "".

看起来通常你确实想要一个 JSON 响应,所以我不会将你的 dataType 更改为“text”,相反,即使响应为空,我也会让服务器返回有效的 JSON 响应,例如“{}”而不是“” .