簡體   English   中英

為函數內的全局變量賦值

[英]Assign a value to global variable inside a function

我有一個問題是為全局變量賦值並在函數內部使用它。 這是我的代碼:

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

警報失敗,因為您的請求尚未完成。 你可以試試這個:

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

http://jsfiddle.net/ZpUsM/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM