簡體   English   中英

如何從另一個文件中加載數據作為JavaScript / jQuery中的選項值?

[英]How to load data from another file as an option value in JavaScript / jQuery?

考慮下面的代碼:

$(".sceditor").sceditor({
    emoticons: // contents from another file here
});

我想加載另一個包含JSON對象作為emoticons選項值的文件。

我嘗試了以下方法:

$(".sceditor").sceditor({
    emoticons: $.getJSON('../../images/emoticons/default/emoticons.json')
});

但這不起作用,因為它returnsJQXHR對象,而不是JSON對象。

為了獲得價值,我相信我需要做一些事情:

$(".sceditor").sceditor({
    emoticons: $.getJSON('../../images/emoticons/default/emoticons.json', function(response) {
        // response is the JSON object
    })
});

但是顯然這是行不通的,因為response變量位於匿名函數內部,並且沒有返回成為emoticons值的值。

我知道我可以將整個sceditor調用包裝在$.getJSON調用中,但是我真的不希望整個代碼都依賴於對圖釋文件的成功調用。

然后,我想到了在此之上執行此操作:

$.getJSON('../../images/emoticons/default/emoticons.json', function(response) {
    var foo = response;
})

...但是如何在范圍外訪問foo

通常,什么是我要完成的最佳方法?

我將在jqxhr對象上使用.done().always() promise方法來完成此任務。

這聽起來像你想要的是初始化sceditor不管你是否有表情與否。 但是,如果您能夠加載表情符號,那么您想使用那些表情符號。

這是一個快速的解決方案,顯示了如何使用Promise方法來實現所需的結果。 顯然,您可以擴展並使其變得更好,但這可以作為起點。

    // create a variable to store the results
    var emoticons = false;

    $.getJSON('../../images/emoticons/default/emoticons.json')
    .done(function(result){
        emoticons = result;
    })
    .always(function(){
        // always initialize the sceditor
        $('.my-selector').sceditor({emoticons: emoticons}); 
    });

和必要的jsFiddle: http : //jsfiddle.net/oLspfLby/1/

您可以在外部范圍內定義變量,將其填充在getJSON響應函數中,並在其他代碼中使用

var foo;
$.getJSON('../../images/emoticons/default/emoticons.json', function(response) {
    foo = response;
});

$(".sceditor").sceditor({
    emoticons: foo
});

暫無
暫無

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

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