这就是我目前所拥有的,如果请求超时,则不会返回任何消息。
$.getJSON(jsonUrl, function(data){
/*here*/
if (data.stat != "ok") { //checks if query was valid
$('#content').html('content not available');
return;
}
else {...Do Code...}
});
我的问题是,如果未返回 Json feed,我可以(以及如何)要求 Jquery 重试最多 2 次,如果返回 feed,我如何检查 json 数据本身是否有错误并且在正确的 json 语法。
最后,/*here*/
之后的所有内容都在返回整个提要后立即执行吗?
最佳答案
根据documentation ,如果返回格式错误的 json,$.getJSON
通常会默默失败:
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.
至于重试请求最多两次,应执行以下操作:
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
}
是的,一旦服务器返回内容,/*here*/
之后的所有内容都会被执行。
关于javascript - 使用 Jquery 确定 Json feed 状态和数据有效性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2261963/