最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Should I wait for ajax to complete to redirect a page? - Stack Overflow

programmeradmin4浏览0评论

I know how to wait for ajax to plete, but if I'm going to redirect a page after some ajax calls are fired off, should I wait for them to plete before the redirect? Does it matter?

I know how to wait for ajax to plete, but if I'm going to redirect a page after some ajax calls are fired off, should I wait for them to plete before the redirect? Does it matter?

Share Improve this question asked Jul 18, 2013 at 23:31 elijahelijah 2,9241 gold badge19 silver badges23 bronze badges 1
  • 5 I guess that depends if you need to do some errorhandling around the status code returned by the ajax call. If you redirect before it finishes how would you know it went through correctly? – JanR Commented Jul 18, 2013 at 23:33
Add a ment  | 

3 Answers 3

Reset to default 6

If you're confident that the ajax call will be successful, then once the ajax call has occurred, redirecting won't affect it as far as your server is concerned. But don't forget, the client could lose their connection or a number of errors could occur, so you should probably wait to make sure the calls were successful. Another thing to consider is whether or not your ajax calls will affect whatever page you're going to redirect to. In that case DEFINITELY wait before redirecting. You won't want your user to get redirected to a broken page because their connection was slow or your server had a hiccup.

I remend waiting and handling possible errors that might occur.

You gain safe connection, error spotting, better software, by doing the whole process synchronously, making the redirection ing in the end.

You might spend 0.1 second more of execution but who cares?

I would argue that Ajax followed by a redirect is not a good use case for Ajax. Instead I would remend doing a regular server request and then take care of all operations on the server before redirecting to your final destination.

This will make for a simpler pattern and a lot less network traffic. I remend to use Ajax in cases where you want to avoid reloading the page. However in your scenario, you are planning on leaving the page as soon as your operations have pleted, so why not avoid the back and forth that Ajax will give you.

发布评论

评论列表(0)

  1. 暂无评论