javascript - 使用 Jquery 确定 Json feed 状态和数据有效性

标签 javascript jquery ajax json validation

这就是我目前所拥有的,如果请求超时,则不会返回任何消息。

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

相关文章:

php - 我如何使其面向对象?

javascript - 切换查询字符串变量

javascript - 如何在js中使用.match(regEx)仅获取没有分隔符的内部字符串?

javascript - 在 JavaScript 中自动选择和检索复选框值

javascript - 防止 jQuery 通过 .clone() 创建重复的克隆

javascript - 循环遍历多层 json Jquery

jquery - ajax 调用后 HTML 数据和内容丢失

javascript - 在文本字段中输入时更新 div

javascript - 处理Promise中的错误

javascript - ExtJS MVC 表单引用