简体   繁体   English

我应该等待ajax完成重定向页面吗?

[英]Should I wait for ajax to complete to redirect a page?

I know how to wait for ajax to complete, but if I'm going to redirect a page after some ajax calls are fired off, should I wait for them to complete before the redirect? 我知道如何等待ajax完成,但是如果我要在一些ajax调用被触发后重定向页面,我应该等待它们在重定向之前完成吗? Does it matter? 有关系吗?

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. 如果你确信ajax调用会成功,那么一旦发生ajax调用,就服务器而言,重定向不会影响它。 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. 另一件需要考虑的事情是你的ajax调用是否会影响你要重定向到的任何页面。 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 recommend 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 coming in the end. 通过同步完成整个过程,您可以获得安全连接,错误定位,更好的软件,使重定向最终到来。

You might spend 0.1 second more of execution but who cares? 您可能会花费0.1秒的执行时间,但是谁在乎呢?

I would argue that Ajax followed by a redirect is not a good use case for Ajax. 我认为Ajax后面的重定向不是Ajax的一个很好的用例。 Instead I would recommend 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 recommend to use Ajax in cases where you want to avoid reloading the page. 我建议在您希望避免重新加载页面的情况下使用Ajax。 However in your scenario, you are planning on leaving the page as soon as your operations have completed, so why not avoid the back and forth that Ajax will give you. 但是在您的方案中,您计划在操作完成后立即离开页面,那么为什么不避免Ajax会给您带来的反复。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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