[英]Assign a value to global variable inside a function
I have a problem assigning a value to a global variable and using it inside of a function. 我有一个问题是为全局变量赋值并在函数内部使用它。 Here is my code:
这是我的代码:
var chartinfo = {"c0":"0", "c1":"0"}; // This is my global variable
$.getJSON("http://127.0.0.1:8080/chartinfo", function(json1){
chartinfo = json1; // I need to assign json1's value to chartinfo
});
$(function () {
$(document).ready(function() {
alert("external chartinfo " + chartinfo.c0.name); // I need to use chartinfo here
The alert fails because your request is not finished yet. 警报失败,因为您的请求尚未完成。 You could try this:
你可以试试这个:
var chartinfo = {
"c0": "0",
"c1": "0"
};
var jqxhr = $.getJSON("http://127.0.0.1:8080/chartinfo", function (json1) {
console.log("success");
})
.done(function () {
chartinfo = json1;
alert("external chartinfo " + chartinfo.c0.name); // I need to use chartinfo here
})
.fail(function () {
console.log("error");
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.