将Ajax结果分配给Javascript中的全局变量 [英] Assign Ajax result to global variable in Javascript

查看:88
本文介绍了将Ajax结果分配给Javascript中的全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个发送AJAX请求并返回表示令牌记录JSON string的结果的方法,我正在尝试获取此结果并将其分配给名为tokens的全局变量,然后重用此方法其他函数中的全局变量.

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);
                }
            });
        }

问题是,当我将结果分配给变量,然后将其记录到控制台时,它成功显示了结果,但是当我以后想要在其他函数中重用它时,则表明变量仍然是null

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.

例如,我想在下面的jQuery代码中使用它,但是它显示变量为空:

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}

有什么建议吗?

推荐答案

在全局使用变量之前,请确保AJAX回调已完成

大多数情况下,当您尝试通过AJAX获取值然后尝试在整个$.ajax()构造之外使用该值时,都会出现问题.原因是异步调用的响应只能在其successcomplete回调中安全地访问-无法保证在这些回调中的任何一个完成之前,将填充该值.要解决此问题,您可以将所有以下代码从AJAX回调内部调用,也可以等待回调设置全局变量.

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.

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
    });
}

使用使用脚本来等待变量

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);
    }
}

然后您可以致电:

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

当心:如果您的AJAX响应时间真的很长,这可能会导致浏览器明显挂起,并有效地将异步调用转换为同步调用.希望这对您目前的状况有所帮助!

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!

这篇关于将Ajax结果分配给Javascript中的全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆