Error handling in getJSON calls

后端 未结 9 1635
野的像风
野的像风 2020-11-28 02:09

How can you handle errors in a getJSON call? Im trying to reference a cross-domain script service using jsonp, how do you register an error method?

9条回答
  •  情深已故
    2020-11-28 02:25

    I know it's been a while since someone answerd here and the poster probably already got his answer either from here or from somewhere else. I do however think that this post will help anyone looking for a way to keep track of errors and timeouts while doing getJSON requests. Therefore below my answer to the question

    The getJSON structure is as follows (found on http://api.jqueri.com):

    $(selector).getJSON(url,data,success(data,status,xhr))
    

    most people implement that using

    $.getJSON(url, datatosend, function(data){
        //do something with the data
    });
    

    where they use the url var to provide a link to the JSON data, the datatosend as a place to add the "?callback=?" and other variables that have to be send to get the correct JSON data returned, and the success funcion as a function for processing the data.

    You can however add the status and xhr variables in your success function. The status variable contains one of the following strings : "success", "notmodified", "error", "timeout", or "parsererror", and the xhr variable contains the returned XMLHttpRequest object (found on w3schools)

    $.getJSON(url, datatosend, function(data, status, xhr){
        if (status == "success"){
            //do something with the data
        }else if (status == "timeout"){
            alert("Something is wrong with the connection");
        }else if (status == "error" || status == "parsererror" ){
            alert("An error occured");
        }else{
            alert("datatosend did not change");
        }         
    });
    

    This way it is easy to keep track of timeouts and errors without having to implement a custom timeout tracker that is started once a request is done.

    Hope this helps someone still looking for an answer to this question.

提交回复
热议问题