[英]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')
});
但這不起作用,因為它returns
是JQXHR
對象,而不是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.