改变页面之前Ajax调用? [英] ajax call before changing page?

查看:67
本文介绍了改变页面之前Ajax调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如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;
    }
});

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆