简体   繁体   English

如何发送ajax请求并重定向到另一个页面

[英]How can I send an ajax request and redirect to another page

I have seen the following sequence in my client code: 我在客户端代码中看到了以下顺序:

$.ajax({
    url: "...",
    data: {},
    success: function() {
    // I don't care about the response
    }
});

top.location.href="http://...." 

As you can see the browser send an ajax request, and doesn't care about the response. 如您所见,浏览器发送了一个ajax请求,并且不在乎响应。 after it sends the request the page is redirected to another url using the top.location.href statement . 发送请求后,使用top.location.href语句将页面重定向到另一个URL。

I am a newbie in javascript and I am not sure if the ajax request is guaranteed to be sent? 我是javascript的新手,不确定是否可以发送ajax请求?

Is there another approach to get this send and forget and redirect ajax behavior? 是否有另一种方法来使该发送和忘记以及重定向 ajax行为?

EDIT : 编辑

Just to clarify, I do not want to wait for this ajax to finish it's long operation and put the redirection line in the success callback. 只是为了澄清,我不想等待此ajax完成它的长时间操作,并将重定向行放入成功回调中。

If you want to be 100% sure that the message was received and processed, you should do your redirect in the success handler. 如果要100%确保已收到并处理了该消息,则应在success处理程序中进行重定向。

This would also enable you to do error handling if that is required - for example, what if you make the AJAX request but it fails for some reason? 如果需要的话,这还使您能够进行错误处理-例如,如果您发出AJAX请求但由于某种原因失败了怎么办? If you just redirect the user would never know there was a problem. 如果您只是重定向,用户将永远不会知道有问题。 But maybe you do not need to care about this depending upon this specifics of your application. 但是,也许您不必根据应用程序的具体情况来关心它。

如果您只想在ajax请求成功后重定向到其他页面,那为什么不将top.location放在成功函数中,或者如果您只是想重定向而无论ajax是否成功,请在...中写入top.location完整参数的功能。

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

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