簡體   English   中英

動態加載json文件-JavaScript

[英]Load json file dynamically - javascript

請檢查以下內容:

    var scripts = {};

require = function(src){
    var id = Math.round(+new Date()/1000);

    $.ajax({
        url: src + '.json',
        type: 'GET',
        dataType: "json",
        cache: false,
                    async: false,
        success : function(data){
            scripts[id] = data;
        }
    });

    return scripts[id];
}

返回undefined:/有什么問題!? 我不知道...

編輯! 'async:false'並運行!

這是因為$ .ajax在您的調用中是異步的。

return scripts[id];

上面的行甚至在觸發success回調之前執行。

這是一個異步調用。 返回時腳本為空。

查明原因,

window.scripts = {};

require = function(src){
var id = Math.round(+new Date()/1000);

$.ajax({
    url: src + '.json',
    type: 'GET',
    dataType: "json",
    cache: false,
    success : function(data){
        window.scripts[id] = data;
        alert(window.scripts)
    }
});

//return scripts[id];

}

警報后,請參閱window.scripts的值

它的異步問題.. Ajax調用被異步調用。

return scripts[id];

在ajax調用返回之前執行

您的問題是該調用是異步的。 這意味着您的方法將在調用完成之前返回。

而不是返回腳本[id],請嘗試以下方法:

require = function(src){
    var id = Math.round(+new Date()/1000);

    $.ajax({
        url: src + '.json',
        type: 'GET',
        dataType: "json",
        cache: false,
        success : function(data){
            scripts[id] = data;
            DoStuff(scripts[id]);
        }
    });
}

DoStuff(data) {
    // do whatever it is you were going to do after the return.
}

暫無
暫無

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

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