Aborting jQuery JSONP request will throw error

后端 未结 3 610
臣服心动
臣服心动 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);
        }
      });
    
    }
    

提交回复
热议问题