简体   繁体   中英

Cancel a request using jquery.Ajax()

I am currently setting up a projects page with a series of links to project images, these images are loaded in using jquery load at the moment. However if I click a link then click a different link in quick succession it seems to load the images from the first link rather than cancelling that request and loading the second link

I gather from what I have been reading that the best method use would be to swap jquery load for jquery Ajax, the only issue is that I don't quite understand how to achieve this with jquery ajax, I would be grateful if someone could give me a starting point

Thanks

You will probably want to read: Abort Ajax requests using jQuery They explain that very thing. For some reason, StackOverflow wants to convert this to a comment, not an answer, so I've added this sentence.

I'm assuming right now, you're calling something like this:

$('#mydiv').load('projects.php?page=1');

The exact equivalent using ajax() would be:

$.ajax('projects.php?page=1', {
  success: function(html) {
    $('#mydiv').html(html);
  }
});

I'm guessing people told you that you would want to abort the old request and start a new one? You can do that by saving the jqXHR object returned by ajax() and using it later:

var jqXHR = $.ajax('first url', ...);

// Later
jqXHR.abort();
var jqXHR = $.ajax('second url', ...);

Hopefully that's enough to get you started, let me know if you have questions.

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