Getting AJAX response body for use in error callback

前端 未结 4 2083
鱼传尺愫
鱼传尺愫 2020-12-10 00:08

jQuery\'s AJAX error function has the following parameters:

error(XMLHttpRequest, textStatus, errorThrown)

What\'s the best cross-browser w

相关标签:
4条回答
  • 2020-12-10 00:53

    One straightforward usage example with jQuery:

    var url = '/';
    $.get(url).then(
      function(response) {
          $("#result").html(response);
      },
      function(jqXHR) {
        $("#result").html('Error occurred: '+ jqXHR.statusText + ' ' + jqXHR.status);
      }
    ); 
    

    This should return the HTML of current website front page.

    Then try entering a nonsense URL that doesn't exist and see the error thrown. You should get "404 Not Found" from web server. Test it: JSFiddle here

    0 讨论(0)
  • 2020-12-10 01:01

    As of jQuery 1.4.1 you should use:

    var json = JSON.parse(xhr.responseText);
    

    See http://api.jquery.com/jQuery.parseJSON/.

    0 讨论(0)
  • 2020-12-10 01:02

    There is a hidden function that can extract the data from XHR istance:

    var responseText = $.httpData(xhr)
    

    If you pass "json" as a second parameter it will treat the response as a JSON string.

    Note that you might get an error because there is no response (network problem for example). Make sure you cover that case as well. Also, I believe (not sure) that jQuery invokes the error handler if the server returns a 4xx or 5xx status.

    0 讨论(0)
  • 2020-12-10 01:12

    For a more recent and general answer (since jquery 1.5), I'd use the jqXHR object:

    $.ajax(url).fail(function(jqXHR, textStatus, errorThrown) {
        alert(jqXHR.responseText);
    })
    

    Alternatively responseJSON can be used to get the response body already parsed

    $.ajax(url).fail(function(jqXHR, textStatus, errorThrown) {
        console.log(jqXHR.responseJSON);
    })
    
    0 讨论(0)
提交回复
热议问题