How to detect JQuery $.get failure? Seeking simple code example

前端 未结 3 782
旧巷少年郎
旧巷少年郎 2020-12-25 11:04

I\'m a JQuery n00b. I\'m trying to code a very simple using $.get(). The official documentation says

If a request with jQuery.get() returns an error code, it wi         


        
相关标签:
3条回答
  • 2020-12-25 11:38

    .get() is just a synonym for .ajax() with a number of options pre-set. Use ajax() to get the full range of options, including the error callback.

    $.ajax({
    type: "GET",
    url: "test.htm",
    error: function(xhr, statusText) { alert("Error: "+statusText); },
    success: function(msg){ alert( "Success: " + msg ); }
    }
    );
    
    0 讨论(0)
  • 2020-12-25 11:41

    You're right that you can use jQuery 1.5's new jqXHR to assign error handlers to $.get() requests. This is how you can do it:

    var request = $.get('/path/to/resource.ext');
    
    request.success(function(result) {
      console.log(result);
    });
    
    request.error(function(jqXHR, textStatus, errorThrown) {
      if (textStatus == 'timeout')
        console.log('The server is not responding');
    
      if (textStatus == 'error')
        console.log(errorThrown);
    
      // Etc
    });
    

    You can also chain handlers directly onto the call:

    $.get('/path/to/resource.ext')
         .success(function(result) { })
         .error(function(jqXHR, textStatus, errorThrown) { });
    

    I prefer the former to keep the code less tangled, but both are equivalent.

    0 讨论(0)
  • 2020-12-25 11:52

    As of jQuery 3.0 .success() and .error() are depreciated.
    You can use .done() and .fail() instead

    $.get( url )
        .done(function( data, textStatus, jqXHR ) {
            console.log(data);
        })
        .fail(function( jqXHR, textStatus, errorThrown ) {
            console.log(jqXHR);
            console.log(textStatus);
            console.log(errorThrown );
        });
    

    Source: https://api.jquery.com/jQuery.ajax/

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