获取变量的ajax完成后,变量、完成后、ajax

2023-09-10 13:24:26 作者:至少还有你陪我到最后

我有这个$ C $下做出一些要求我的服务器:

I have this code for make some request to my server:

function myAjaxCheck(token) {
        $.ajax({
            type: 'POST',
            url: 'auth.php',
            data: {
                token: token,
            },
            dataType: 'json',
            success: function (data) {
                if (data.auth == 'OK') {
                    alert ('ok');
                    }
                } else {
                    alert('Error: ' + data.auth);
                }
            }
        }).done(function (data) {
            return data;
        });
    }

所以,我需要返回的数据传递到像一个变量:

So, i need to pass the returned data into a variable like:

Var MyVariable = myAjaxCheck(token);
console.log(MyVariable);

在控制台:

未定义

哪里出了问题,应该将数据返回完成时,却并非如此。

at console:

undefined

Where is the problem, is supposed to data will returned when done, but isn't.

推荐答案

默认情况下,阿贾克斯()请求是异步所以调用阿贾克斯()通常会返回请求完成之前。你可以使用一个回调函数。

By default, an ajax() request is asynchronous so the call to ajax() will usually return before the request completes. You could make use of a callback function instead.

function myAjaxCheck(token, callback) {
        $.ajax({
            type: 'POST',
            url: 'auth.php',
            data: {
                token: token,
            },
            dataType: 'json',
            success: function (data) {
                if (data.auth == 'OK') {
                    alert ('ok');
                    }
                } else {
                    alert('Error: ' + data.auth);
                }

                callback(data);
            }
        });
    }

var myVariable; 
 myAajxCheck(token, function(returnedData){ //anonymous callback function
    myVariable = returnedData;
    console.log(myVariable);
 });

如果你绝对必须,您可以使用 异步:假电话里面阿贾克斯()

If you absolutely must, you could use async: false inside the call to ajax().