简体   繁体   中英

Assign Ajax result to global variable in Javascript

I have a method that sends AJAX request and returns a result that indicates a JSON string of Tokens records, I'm trying to get this result and assign it to a global variable called tokens and then reuse this global variable in other functions.

I'm assigning the result to that variable and log it to the console as follows:

var tokens = null;


function PopulateAllTokens() {
            $.ajax({
                type: "POST",
                url: "NewToken.aspx/PopulateAllTokens",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    alert("Request: " + JSON.stringify(XMLHttpRequest) + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
                },
                success: function (result) {
                    tokens = JSON.parse(result.d);
                    console.log(tokens);
                    populateTokensToTable(tokens);
                }
            });
        }

The issue is that, when I assign the result to the variable and then log it to the console it shows the result successfully, but when I want to reuse it later in other functions it shows that the variable is still null .

For example I want to use it in the following jQuery code but it shows that the variable is null:

$("#example").DataTable({
        "columns": getTokens(),
        "data": tokens
    });

Just to clarify that both variable and function are being defined inside:

$(document).ready(function () {//function and var}

Any suggestions please?

Make sure the AJAX callback has finished before using the variables globally

Most of the time problems arise when you try to get a value via AJAX and then try to use that value outside the whole $.ajax() construct. The reason is that responses from async calls can only be accessed safely inside their success or complete callbacks - there is no guarantee the value will be populated before either of those callbacks complete. To work around this, you can either move all following code to be called from inside the AJAX callback, or wait for your global vars to be set by the callback.

Using the callback to continue running your script

var tokens = null;

function PopulateAllTokens() {
    $.ajax({
        type: "POST",
        url: "NewToken.aspx/PopulateAllTokens",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert("Request: " + JSON.stringify(XMLHttpRequest) + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
        },
        success: function (result) {
            tokens = JSON.parse(result.d);
            console.log(tokens);
            populateTokensToTable(tokens);

            EverythingElseYouWantToRun();
        }
    });
}

function EverythingElseYouWantToRun() {

    // you can do whatever you want with the response here

    $("#example").DataTable({
        "columns": getTokens(),
        "data": tokens
    });
}

Await the variable with your consuming script

var tokens = null;

function PopulateAllTokens() {
    $.ajax({
        type: "POST",
        url: "NewToken.aspx/PopulateAllTokens",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert("Request: " + JSON.stringify(XMLHttpRequest) + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
        },
        success: function (result) {
            tokens = JSON.parse(result.d);
            console.log(tokens);
            populateTokensToTable(tokens);
        }
    });
}

function RunWhenVariableIsPopulated(variable, callback, timeout) {

    if (variable === null) {

        setTimeout(function() {

            RunWhenVariableIsPopulated(variable, callback, timeout);
        }, timeout);

    } else {

        callback(variable);
    }
}

Then later you can call:

RunWhenVariableIsPopulated(tokens, function() {
    $("#example").DataTable({
        "columns": getTokens(),
        "data": tokens
    });
}, 400 /* or whatever your average round-trip time is*/);

Beware: this can cause the browser to hang noticeably if your AJAX response time is really long, and effectively turns an async call into a synchronous one. Hope this helps with your current situation!

function getData(){
return $.ajax({
            type: "POST",
            url: "NewToken.aspx/PopulateAllTokens",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            async: false,
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert("Request: " + JSON.stringify(XMLHttpRequest) + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
            },
            success: function (result) {
                tokens = JSON.parse(result.d);
                console.log(tokens);
                populateTokensToTable(tokens);
            }
        }).responseText;
}

var res = getData();

Above code will store the response in the variable and after that you can parse it and modify as you need. I am not sure, but It may help you

use $.parseJSON() Method

$(document).ready() is doesn't matter, only thing is functions calls flow, you can declare the function outside also and call it accordingly, and also its good to check the variable null or not like

var tokens = null;

function PopulateAllTokens() {
            $.ajax({
                type: "POST",
                url: "NewToken.aspx/PopulateAllTokens",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    alert("Request: " + JSON.stringify(XMLHttpRequest) + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
                },
                success: function (result) {
                    tokens = $.parseJSON(result.d);
                    console.log(tokens);
                    populateTokensToTable(tokens);
                }
            });
        }

    if(tokens)
       console.log(tokens);

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