考虑以下代码:
$(".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;
})...but,那么我如何访问范围之外的foo?
一般情况下,做我想要完成的事情的最好方法是什么?
发布于 2015-06-11 15:00:17
我将在.done()对象上使用.always()和.always()允诺方法来实现这一点。
听起来你想要的是初始化sceditor,不管你是否有表情符号。但是,如果您能够加载表情符号,那么您希望使用这些。
下面是一个快速解决方案,展示了如何使用承诺方法来实现您想要的目标。显然,您可以扩展并使其更好,但这可以作为一个起点。
// 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/
发布于 2015-06-11 13:09:41
您可以在外部范围内定义变量,在getJSON响应函数中填充变量,并在进一步的代码中使用。
var foo;
$.getJSON('../../images/emoticons/default/emoticons.json', function(response) {
foo = response;
});
$(".sceditor").sceditor({
emoticons: foo
});https://stackoverflow.com/questions/30781692
复制相似问题