将多维JSON对象数组加载到selectize.js中

时间:2015-08-28 16:05:39

标签: javascript jquery json selectize.js

我想将此JSON加载到selectize:

{"platforms":

[{"id":32,"name":"Sega Saturn","slug":"saturn"},

{"id":14,"name":"Mac","slug":"mac"},

{"id":47,"name":"Virtual Console (Nintendo)","slug":"vc"},

{"id":34,"name":"Android","slug":"android"},

{"id":84,"name":"SG-1000","slug":"sg1000"},

{"id":58,"name":"Super Famicom","slug":"sfam"},

{"id":82,"name":"Web browser","slug":"browser"}]

}

我希望它与this example provided by the Selectize.js developers的操作非常相似(不包括每个中的URL部分),除了使用我的json数据显然不是预先制作的ID和名称。

感谢任何帮助。

Code I目前正在尝试使用:

options: [
    for (var i = 0; i < platforms.platforms.length; i++) 
    {
        var counter = platforms.platforms[i];
        {id: counter.id, title: counter.name},
        console.log(counter.name);
    }

以下是在控制台中记录JSON时的样子:

enter image description here enter image description here

编辑: This is another example that I'm looking at as it uses JSON.

2 个答案:

答案 0 :(得分:3)

当您声明变量时,您不能在数组/对象中使用for。 Javascript不是像PHP&amp; HTML这样的模板。

你也错过了.slug。试试这个:

var data = JSON.parse('{"platforms":[{"id":32,"name":"Sega Saturn","slug":"saturn"},{"id":14,"name":"Mac","slug":"mac"},{"id":47,"name":"Virtual Console (Nintendo)","slug":"vc"},{"id":34,"name":"Android","slug":"android"},{"id":84,"name":"SG-1000","slug":"sg1000"},{"id":58,"name":"Super Famicom","slug":"sfam"},{"id":82,"name":"Web browser","slug":"browser"}]}');
var options = [];
$.each(data.platforms, function()
{
    options.push({
        id: this.id,
        title: this.name,
        url: "hhtp://site.com/"+this.slug
    });
});
var $select = $('#select-tools').selectize({
    maxItems: null,
    valueField: 'id',
    labelField: 'title',
    searchField: 'title',
    options: options,
    create: false
});

答案 1 :(得分:2)

您显示的代码有几个语法错误。你不是很熟悉JavaScript,是吗?

@klenium是正确的,无论是在他的建议中,还是通过显示可以独立运行的完整代码。您应该访问像Plunkr或JSFiddle这样的网站,添加正确的导入,在那里运行此代码,如果它没有做您期望的,请在此处添加指向页面的链接,以便我们检查出错了什么。

注意:Selectize的一个兴趣是它可以在没有预处理的情况下获得几乎任何数据,因此代码可能(未经测试!)被简化为:

var $select = $('#select-tools').selectize({
    maxItems: null,
    valueField: 'id',
    labelField: 'title',
    searchField: 'title',
    options: data.platforms, // Just use the Json data as it is
    create: false
});