我有一个服务器端功能,需要登录。如果用户登录成功,函数将返回1。如果不是,该函数将返回登录页面。

我想使用Ajax和jQuery调用该函数。我所做的是提交带有普通链接的请求,并在其上应用了单击功能。如果用户没有登录或函数失败,我希望ajax调用返回true,以便触发href。

但是,当我使用下面的代码时,函数在Ajax调用完成之前退出。

如何将用户优雅地重定向到登录页面?

$(".my_link").click(
    function(){
    $.ajax({
        url: $(this).attr('href'),
        type: 'GET',
        cache: false,
        timeout: 30000,
        error: function(){
            return true;
        },
        success: function(msg){ 
            if (parseFloat(msg)){
                return false;
            } else {
                return true;
            }
        }
    });
});

当前回答

在现代JS中,你可以简单地使用async/await,比如:

  async function upload() {
    return new Promise((resolve, reject) => {
        $.ajax({
            url: $(this).attr('href'),
            type: 'GET',
            timeout: 30000,
            success: (response) => {
                resolve(response);
            },
            error: (response) => {
                reject(response);
            }
        })
    })
}

然后在一个异步函数中调用它,比如:

let response = await upload();

其他回答

底层的XMLHttpRequest对象(由jQuery用于发出请求)支持 异步属性。设置为false。就像

async: false

因为我在这里没有看到它,所以我想我也要指出jQuery when语句在这个目的中非常有用。

他们的例子如下:

$.when( $.ajax( "test.aspx" ) ).then(function( data, textStatus, jqXHR ) {
  alert( jqXHR.status ); // Alerts 200
});

“then”部分直到“when”部分结束才执行。

我认为,如果您将成功函数编码为加载适当的页面,而不是返回true或false,事情就会更容易。

例如,你可以这样做,而不是返回true:

window.location="appropriate page";

这样,当成功函数被调用时,页面被重定向。

它应该等待get请求完成。之后,我将从函数调用的地方返回get请求体。

function foo() {
    var jqXHR = $.ajax({
        url: url,
        type: 'GET',
        async: false,
    });
    return JSON.parse(jqXHR.responseText);  
}

我没有使用$。Ajax和$。Post和$。get函数,所以如果我需要等待响应,我使用这个:

$.ajaxSetup({async: false});
$.get("...");