如何在JavaScript/jQuery中作为选项值从另一个文件加载数据?
考虑以下代码:如何在JavaScript/jQuery中作为选项值从另一个文件加载数据?,javascript,jquery,json,Javascript,Jquery,Json,考虑以下代码: $(".sceditor").sceditor({ emoticons: // contents from another file here }); 我想加载另一个文件,其中包含一个JSON对象作为emoticons选项的值 我尝试了以下方法: $(".sceditor").sceditor({ emoticons: $.getJSON('../../images/emoticons/default/emoticons.json') }); 但这不起作用,因
$(".sceditor").sceditor({
emoticons: // contents from another file here
});
我想加载另一个文件,其中包含一个JSON
对象作为emoticons
选项的值
我尝试了以下方法:
$(".sceditor").sceditor({
emoticons: $.getJSON('../../images/emoticons/default/emoticons.json')
});
但这不起作用,因为它返回JQXHR
对象,而不是JSON
对象
要获得我认为的价值,我需要执行以下操作:
$(".sceditor").sceditor({
emoticons: $.getJSON('../../images/emoticons/default/emoticons.json', function(response) {
// response is the JSON object
})
});
但是显然这不起作用,因为response
变量在匿名函数中,并且不会返回成为表情符号的值
我知道我可以将整个sceditor
调用封装在$.getJSON
调用中,但我并不希望整个代码依赖于对表情文件的成功调用
然后我想在上面做这个:
$.getJSON('../../images/emoticons/default/emoticons.json', function(response) {
var foo = response;
})
…但我如何访问范围外的foo
一般来说,做我想做的事情的最佳方法是什么?您可以在外部范围中定义变量,将其填入getJSON
响应函数,并在后续代码中使用
var foo;
$.getJSON('../../images/emoticons/default/emoticons.json', function(response) {
foo = response;
});
$(".sceditor").sceditor({
emoticons: 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});
});
以及必要的JSFIDLE:
表情符号:function(){$.getJSON('..',function(response){return response;});}
不起作用吗?(这里只是一个想法)。@D4V1D尝试了一下,但没有成功。很遗憾……你有错误吗?输出是什么?@D4V1D没有错误,但也没有加载表情符号;与之前的结果基本相同,它通过NET
面板成功加载文件,但在表情下拉列表中没有显示任何内容。因此,我建议您使用全局变量。使用上一个解决方案,但不要使用var foo=response代码>使用window.foo=response
然后使用表情符号:window.foo,
。