Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/80.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在JavaScript/jQuery中作为选项值从另一个文件加载数据?_Javascript_Jquery_Json - Fatal编程技术网

如何在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,