jQuery ajax call returns empty error if the conten

2020-08-11 07:18发布

问题:

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

回答1:

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...

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:

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 "".