AJAX: Check if a string is JSON?

前端 未结 7 2063
甜味超标
甜味超标 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:20

    Why you can't just check what is the response? It is more more efficient.

    var result;
    
    if (response.headers['Content-Type'] === 'application/json')
        result = JSON.parse(this.responseText);
    else
        result = this.responseText;
    

    screen1

提交回复
热议问题