简体   繁体   中英

Accessing variable from callback using AJAX in jQuery

Code explains all:

//
// … code ...
//
$.ajax({
    dataType: "json",
    url: "foo",
    success: function(data) {
        var my_data = data;
    }
});
//
// … code ...
//
console.log(my_data); // NOT in scope

How do I get access to my_data outside of the AJAX call? I've read that maybe a closure is needed? I can't find any examples that do want I want though.

Many thanks.

Ajax is async call and success may be fired after console.log, you can call a function from success and pass data to it.

$.ajax({
    dataType: "json",
    url: "foo",
    success: function(data) {
        yourFun(data);
    }
});

function yourFun(data)
{
}

To giving function instead of success.

$.ajax({
    dataType: "json",
    url: "foo",
    success: yourFun
});

function yourFun(data)
{
}

Generally speaking, you don't. AJAX calls are asynchronous so there's no guarantee of a value immediately after the jQuery.ajax() function has executed; you need to wait until the AJAX call has completed, and the success callback has executed, before you attempt to use that variable.

The easiest approach is to just use that value inside the success callback. If you really need it to be available outside then make it a variable that's visible to all of your code (not necessarily global, depending on how your code is structured), and check that it has a value before you attempt to use it in any other functions.

Define my_data as global as below,

var my_data;

$.ajax({
    dataType: "json",
    url: "foo",
    success: function(data) {
        my_data = data;
    }
});
//
// … code ...
//
console.log(my_data); // NOT in scope

Declare my_data variable globally..

var my_data = data;

    $.ajax({
        dataType: "json",
        url: "foo",
        success: function(data) {
            my_data = data;
        }
    });

Use my_data as gloabl variable to access data outside of ajax.

var my_data = '';
$.ajax({
    dataType: "json",
    url: "foo",
    success: function(data) {
        my_data = data;
    }
});

console.log(my_data);

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