[removed] How to tell whether AJAX response is JSON

后端 未结 5 1687
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-29 02:22

I\'ve got an AJAX request that expects JSON in response.

But there\'s a possibility that what gets returns may not be JSON, but rather an HTML error page (unfortunat

5条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-12-29 03:11

    jQuery auto-detects the dataType:

    If the response is JSON, a properly behaving application would set the Content-Type to application/json.

    So all you have to do, if the server is well-behaving, is to test if the Content-Type header in the response starts with application/json.

    By chance, jQuery already does this by itself:

    $.get('/foo', function(data, status, xhr, dataType) {
        if ('json' === dataType) {
            // Yay that's JSON !
            // Yay jQuery has already parsed `data` 
        }
    });
    

    jQuery detects the dataType and passes it as 4th parameter of the callback function. If the dataType is JSON, it parsed the JSON string and parses the resulting value as first parameter of the callback.

提交回复
热议问题