简体   繁体   English

在jQuery / javascript中定义全局变量

[英]Define a Global variable in jQuery/javascript

Defining a Global variable in JavaScript/jQuery and getting it later in script. 在JavaScript / jQuery中定义全局变量,然后在脚本中获取它。

But strange it is not working. 但是奇怪的是它没有用。

printing getResult in console giving me undefined . 在控制台中打印getResult给我undefined

but when trying to print getResult just after the assigned value to it, it is giving me accurate value. 但是当尝试在分配给它的值之后立即打印getResult时,它为我提供了准确的值。

Actually i need ajax result at the bottom .. how could i do this..? 其实我需要在底部的ajax结果..我怎么做..?

var getResult;
$.getJSON(url, function(data) {
    //JS statement to Ajax
    //JS statement to Ajax  
    $.ajax({
        type: "post",
        dataType: "json",
        url: urlTo,
        data: dataSend,
        success: function (result, status) {
                getResult = result; 
                console.log(getResult); // getResult is working here
        }
    });

    //JS statement to Ajax
    //JS statement to Ajax  
    $.ajax({
        type: "post",
        dataType: "json",
        url: urlTo2,
        data: dataSend2,
        success: function (result2, status) {

        }
    });

    console.log(getResult); // getResult is not working here. Giving " undefined" result here.
});

JavaScript is synchronous . JavaScript同步的 AJAX is asynchronous . AJAX异步的

Therefore, the console.log(getResult); 因此, console.log(getResult); at the bottom is firing before the following AJAX executes: 在执行以下AJAX之前,底部触发

success: function (result, status) {
    getResult = result; 
    console.log(getResult); // getResult is working here
} 

You can give getResult a default value and test it yourself. 您可以给getResult一个默认值并自己进行测试。

That is because getResult is not defined until the AJAX call is done, it is only declared . 这是因为只有在AJAX调用完成后才定义getResult ,才声明它。

Since AJAX is async, your first console log is like that : 由于AJAX是异步的,因此您的第一个控制台日志是这样的:

var getResult;
console.log(getResult);

Can you give me the value of getResult here? 您可以在这里给我getResult的值吗? No, because it is undefined (well actually its value is undefined , shhh ) 不,因为它是未定义的(实际上它的值是undefinedshhh

On the second AJAX call, you did not assign getResult = result2; 在第二个AJAX调用中,您未分配getResult = result2; causing "undefined" value. 导致"undefined"值。

Also, put the global var = getResult; 另外,将全局var = getResult; inside the getJSON function. getJSON函数中。

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

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