[英]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 ) 不,因为它是未定义的(实际上它的值是
undefined
, shhh )
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.