简体   繁体   English

在 ajax 成功调用之外使用数据

[英]use data outside of ajax success call

I am trying to get the data out of a AJAX success call for use elsewhere in the code.我正在尝试从 AJAX 成功调用中获取数据,以便在代码的其他地方使用。 However, the console.log in the last line returns "undefined" for some reason.但是,由于某种原因,最后一行中的console.log返回“未定义”。 I have also tried JSON.parse() and JSON.stringify() on the data, both of which returned errors.我还在数据上尝试JSON.parse()JSON.stringify() ,它们都返回了错误。

function loadInfo() {
    jQuery(function($) {
        $.ajax({
            type: "POST",
            url: "/admin.php",
            data: {loadInfo: 1},
            dataType: "json",
            success: function(data) {
                getResponse(data);
            }
        })
    });
}

var data;
function getResponse(response) {
    data = response;
}

console.log(data);

However, if I did console.log inside the function...但是,如果我在 function 中执行了 console.log ......

var data;
function getResponse(response) {
    data = response;
    console.log(data);
}

It outputs the data as intended.它按预期输出数据。 I thought the data variable would be global.我认为数据变量将是全局的。 Or is it something else?或者是别的什么?

AJAX stands for Asynchronous Javascript and XML. AJAX 代表异步 Javascript 和 XML。 Asynchronous means that it's issuing a request, but since that might take time to arrive, process and its response to arrive back, it's not waiting for the request to finish, but rather it proceeds with the operations.异步意味着它正在发出请求,但由于这可能需要时间才能到达、处理及其响应才能返回,所以它不是等待请求完成,而是继续操作。

When you do当你这样做

console.log(data);

in your code, the request is still being executed and since it's unfinished, the callback is not executed yet .在您的代码中,请求仍在执行中,由于它尚未完成,因此尚未执行回调。 The callback only executes when the request has successfully completed.回调仅在请求成功完成时执行。

Fix:使固定:

function loadInfo() {
    jQuery(function($) {
        $.ajax({
            type: "POST",
            url: "/admin.php",
            data: {loadInfo: 1},
            dataType: "json",
            success: function(data) {
                getResponse(data);
                console.log(data);
            }
        })
    });
}

var data;
function getResponse(response) {
    data = response;
}

//console.log(data);

The idea is that we need to proceed with the results of the request after it's finished.这个想法是我们需要在请求完成后继续处理请求的结果。 Note, my console.log is not inside getResponse , as it's better to separate result representation from result computing.请注意,我的 console.log 不在getResponse中,因为最好将结果表示与结果计算分开。

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

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