如果内容为空,则jQuery ajax调用返回空错误
问题描述:
我每次在res.reply = 2
时都调用getResult()
函数,但是在某些情况下res
为空.当返回值为空时,调用console.log("error")
.这适用于 jQuery Mobile 的旧版本.现在的版本是 1.3.2 .
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.
function getResult()
{
request = $.ajax({
type: "POST",
url: url,
dataType: "json",
data: {
....
},
error: function() {
console.log("error");
},
success: function(res) {
if(res.reply=='2') {
getResult();
}
}
});
}
答
dataType: "json"
意味着:给我json,别无其他.一个空字符串不是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...
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
}
}
});