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

时间:2021-02-26 20:18:05

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.

每当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();
            }         
        }
    });
}

2 个解决方案

#1


24  

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 
        }
    }
});

#2


0  

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响应,即使响应是空的,例如“{}“ 代替 ””。

#1


24  

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 
        }
    }
});

#2


0  

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响应,即使响应是空的,例如“{}“ 代替 ””。