简体   繁体   中英

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. However, the console.log in the last line returns "undefined" for some reason. I have also tried JSON.parse() and JSON.stringify() on the data, both of which returned errors.

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...

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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