[removed] How to tell whether AJAX response is JSON

后端 未结 5 1688
佛祖请我去吃肉
佛祖请我去吃肉 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 02:54
    try {
        jQuery.parseJson(json_string_here);
    } catch(e) {
       ... malformed json ...
    }
    
    0 讨论(0)
  • 2020-12-29 02:55

    jQuery parseJSON function can be used for this. It will throw an exception then you can catch it go ahead.

    data = '{}';
    try {
        json = $.parseJSON(data);
    } catch (e) {
        // not json
    }
    
    0 讨论(0)
  • 2020-12-29 03:05

    Well, if you are using jQuery and you specify the dataType property of the $.ajax() call to json then jQuery will try to parse the JSON, and if it isn't JSON should call the error() callback.

    $.ajax({
        url: '/my/script.ext',
        dataType: 'json',
        success: function(data, textStatus, jqXHR) { /*YAYE!!*/ },
        error: function(jqXHR, textStatus, errorThrown) { /*AWWW... JSON parse error*/ }
    });
    

    EDIT

    For anyone not using jQuery that lands here, the basic idea is to try and parse it as json and catch the error:

    var data = 'some_data';
    
    try {
        data = JSON.parse(data);
    } catch(e) {
        //JSON parse error, this is not json (or JSON isn't in your browser)
    }
    
    //act here on the the parsed object in `data` (so it was json).
    
    0 讨论(0)
  • 2020-12-29 03:09

    Seems like a good use of try catch:

    try {
       $.parseJSON(input)
    } catch(e) {
       // not valid JSON
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题