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

前端 未结 3 788
旧巷少年郎
旧巷少年郎 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: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.

提交回复
热议问题