Aborting jQuery JSONP request will throw error

后端 未结 3 601
臣服心动
臣服心动 2020-12-09 21:44

i am making simple autosuggestion (autocompleter) plugin with jQuery. Unfortunately i have to use jsonp. It is ok and it works, but when i am aborting request it will throw

相关标签:
3条回答
  • 2020-12-09 22:26

    First of all, use some sequencing logic. This will assure your last request prevails over the old ones. Here you have an example.

    Also, you can take advantage of these $.ajax settings:

    timeout: set a time limit per request and prevent requests fail silently.

    beforeSend: validate some conditions before making the call. Complements sequencing helper.

    As of jQuery 1.5, the beforeSend option will be called regardless of the type of request.
    

    Example:

    function updateResults() {
    
      // Init counter & record current request
      if (!window.reqSeq)  window.reqSeq = 0;
      window.reqSeq +=1;
      var thisRequest = window.reqSeq;
    
      $.ajax({
        url: [..],
        crossDomain: true, 
        contentType: "application/json",
        dataType: 'jsonp',
        timeout: 5000, // give 5 seconds of margin
        data: { [..] },
        beforeSend: function() {
          if(thisRequest < window.reqSeq) {
            return false;
          }
        },
        success: function(data, textStatus, jqXHR) {
          if(thisRequest < window.reqSeq) {
            return;
          }
          else print(data);
        },
        error: function(jqXHR, textStatus, errorThrown) {
          // it'll be called on timeout (error) and beforeSend (abort)
          print(textStatus);
        }
      });
    
    }
    
    0 讨论(0)
  • 2020-12-09 22:29

    JSONP does not use XMLHTTPRequest but actually creates a <script> tag within the document to be able to make the cross-domain requests.

    You simply cannot abort JSONP requests.

    It is stated in the $.ajax() documentation:

    Some types of Ajax requests, such as JSONP and cross-domain GET requests, do not use XHR; in those cases the XMLHttpRequest and textStatus parameters passed to the callback are undefined.

    As for jQuery 1.5+, previously was returning the XHR object from $.ajax(), now it returns a superset jqXHR object which encapsulates the XHR object.

    When the transport mechanism is something other than XMLHttpRequest (for example, a script tag for a JSONP request) the jqXHR object simulates native XHR functionality where possible.

    So it returns an object but some functionnalities are actually not available, like .abort().


    The plugin jQuery-JSONP seems to offer the possibility to manually abort JSONP requests. I haven't used it myself but it's worth giving it a try.

    0 讨论(0)
  • 2020-12-09 22:39

    jQuery uses a <script> tag to implement JSONP. You cannot abort the loading of script tags.

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