如果内容为空,jQuery ajax调用返回空错误
每当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(); } } }); }
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 } } });
看起来通常你想要一个JSON响应,所以我不会将你的dataType更改为“text”,而是我会让服务器返回一个有效的JSON响应,即使响应为空,例如“{}”而不是“” 。