改变页面之前Ajax调用? [英] ajax call before changing page?
问题描述
例如code:
$.ajax({
url: someUrl,
data: someData,
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function () { },
});
window.location = urlToGoTo;
可以说,上述code运行时,用户点击一个按钮。
Lets say the above code runs when the user clicks a button.
由于Ajax调用是异步的,什么都会code等以上运行时发生的呢?使用像小提琴手的工具,它看起来像有时AJAX调用成功,有时它永远不会被调用(Ajax调用得到机会运行前,即当前网页被更改)。
Since the ajax call is asynchronous, what will happen when code such the above runs ? Using a tool like Fiddler, it looks like sometimes the ajax call succeeds, and sometimes it never gets called (i.e. the current web page is changed before the ajax call gets a chance to run).
在这样的情况下,你应该总是等待AJAX调用设置window.location(例如,在阿贾克斯完整的事件)之前完成?
In cases like this, should you always wait for the ajax call to complete before setting window.location (e.g. in the ajax "complete" event) ?
只是想获得一些洞察到发生了什么引擎盖下。
Just trying to get some insight into what is happening under the hood.
推荐答案
您可以做重定向的成功回调
You can do the redirect in the success callback
$.ajax({
url: someUrl,
data: someData,
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function () {
window.location = urlToGoTo;
}
});
- 如何返回一个异步调用的响应<? / A>
这篇关于改变页面之前Ajax调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!