views:

95

answers:

1

this is currently what i have, if the request times out there is no message returned.

$.getJSON(jsonUrl, function(data){
        /*here*/
        if (data.stat != "ok") { //checks if query was valid
            $('#content').html('content not available');
            return;
        }
        else {...Do Code...}
 });

My question is, can I (and how) ask Jquery to retry up to 2 more times if the Json feed is not returned, and if the feed is returned how do i check if the json data itself is not faulty and in correct json syntax.

Finally does everything after /*here*/ execute right after the entirety of the feed is returned?

A: 

According to the documentation, $.getJSON will usually fail silently if malformed json is returned:

If there is a syntax error in the JSON file, the request will usually fail silently. Avoid frequent hand-editing of JSON data for this reason.

As for retrying the request up to two more times, the following should do it:

function getJson() {
    var json = (function () {
        var json = null;
        $.ajax({
            'type': 'GET',
            'async': false,
            'global': false,
            'url': '/some/url',
            'dataType': "json",
            'success': function (data) {
                json = data;
            }
        });
        return json;
    })();
    return json;
}

var json = getJson();
if(json.stat != "ok") {
    for(var i = 0; i < 2; i++) {
        json = getJson();
        if(json.stat == "ok") {
            break;
        }
    }
}

if(json.stat != "ok") {
    $('#content').html('content not available');
} else {
    // do stuff with json
}

And yes, everything after /*here*/ is executed as soon as the server returns something.

karim79
thank you so much Karim79! i'm also looking at this http://plugins.jquery.com/project/JSONSchemaValidator which seems to validate the json schema itself : )
Mohammad