如果内容为空,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
jQuery ajax call returns empty error if the content is empty
提问by user2632980
I call the getResult()
function everytime when res.reply = 2
, but there are cases that res
is 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 响应,例如“{}”而不是“” .