AJAX: Check if a string is JSON?

前端 未结 7 2053
甜味超标
甜味超标 2020-12-02 21:32

My JavaScript sometimes crashes on this line:

var json = eval(\'(\' + this.responseText + \')\');

Crashes are caused when the argument of <

7条回答
  •  渐次进展
    2020-12-02 22:29

    If you include the JSON parser from json.org, you can use its parse() function and just wrap it in a try/catch, like so:

    try
    {
       var json = JSON.parse(this.responseText);
    }
    catch(e)
    {
       alert('invalid json');
    }
    

    Something like that would probably do what you want.

提交回复
热议问题