简体   繁体   中英

jQuery AJAX Calls - Is it possible to cancel unwanted calls?

I just wanted to ask. I have text input to allow users to type their city.

jQuery has a keyup event linked to this input and sent an AJAX call after each character change.

I find however many unrequired AJAX calls are sent as the person is typing and depending on the number of results this can slow down performance here.

Is there a way to cancel AJAX calls if a new call is made? Is there a better way to do this?

An example can be seen here: www.datingjapan.co

You can use the abort method of the jqXHR object returned by the ajax method (other AJAX methods like get and post return a jqXHR instance too):

var xhr = $.ajax(opts);
xhr.abort();

Note that the jqXHR object is effectively just an extension of XMLHttpRequest , and XMLHttpRequest itself also has an abort method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM