检查ajax是否返回了有效的json字符串

时间:2016-04-26 13:38:27

标签: jquery json ajax

我在SO上找到了几个相似的答案,但没有一个是足够的。我正在使用$.post()调用ajax并返回json-string。

可能会发生很多事情(json格式不正确,服务器端错误,连接丢失等),如果返回的字符串json有效,我正在尝试测试。

我检查了这个answer,但它正在使用eval,这是不安全的。

这是我的代码,我现在写了:

$.post(
    'some_url.php',
    some_params,
    function(data) {
        var is_JSON = true;

        try {
            data = $.parseJSON(data);
        }
        catch(err) {
            is_JSON = false;
        }

        if (is_JSON && (data !== null)) {
            console.log('correct json format');

            if (data.result === 'OK') {
                console.log('result: OK');
            }
            else if (data.result === 'ERR') {
                console.log('result: ERR');
            }
        }
        else {
            try {
                console.log('incorrect json format');
            }
            catch(err) {
                console.log('error occured');
            }
        }
    }
);

如果返回的字符串是正确的json格式,我怎么能简单地(并且足够)检查?感谢。

1 个答案:

答案 0 :(得分:1)

JSON.parse()怎么样?

$.post(
    'some_url.php',
    some_params,
    function(data) {
            try {
                console.log(JSON.parse(data));
            }
            catch(err) {
                console.log('error occured');
            }
    }
);
相关问题