Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
404 views
in Technique[技术] by (71.8m points)

ajax - jquery::ajaxStop() versus jquery::ajaxComplete()

Which is to be used at which time.

In the documentation on http://api.jquery.com/:

For ajaxStop() it says:

Description: Register a handler to be called when all Ajax requests have completed. This is an Ajax Event.

And for the ajaxComplete() it says:

Description: Register a handler to be called when Ajax requests complete. This is an Ajax Event.

From what I can see ajaxComplete() is more flexible due to:

All ajaxComplete handlers are invoked, regardless of what Ajax request was completed. If we must differentiate between the requests, we can use the parameters passed to the handler. Each time an ajaxComplete handler is executed, it is passed the event object, the XMLHttpRequest object, and the settings object that was used in the creation of the request.

Can someone explain what each is for and the appropriate usage for each. In an application I built recently I relied on ajaxStop() to fire when my ajax calls were finished. I would then parse the returned data for result of server side operation. Now I am starting to wonder if I should have used ajaxComplete() instead or a combination of both for various situations.

Thoughts are appreciated.

question from:https://stackoverflow.com/questions/4419241/jqueryajaxstop-versus-jqueryajaxcomplete

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Well, the short version is they serve different purposes, so the answer would be the "a combination of both for various situations" option. The basic rules are:

  • .ajaxComplete() - runs for every request that completes, use this when you want to do something with each request/result. Note that this doesn't replace the success handler, since the parsed data is not one of the arguments (and it runs even when there's an error) - you may want .ajaxSuccess() in some per-request situations instead.
  • .ajaxStop() - runs when every batch of requests completes, usually you'd use this in combination with .ajaxStart() for things like showing/hiding a "Loading..." indicator of some sort - or to do something else once a batch of AJAX requests finishes, like a master last step.

If you're using this to parse your data, there's probably a better way, in this case $.ajaxSetup(), where you can specify a success handler that gets the already-parsed data (e.g. JSON responses will be objects), like this:

$.ajaxSetup({
  success: function(data) { 
    //do something with data, for JSON it's already an object, etc.
  }
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...