【问题标题】:Calling values from local JSON file using JQuery Typeahead Plugin使用 JQuery Typeahead 插件从本地 JSON 文件调用值
【发布时间】:2015-11-24 20:08:48
【问题描述】:

我正在尝试使用 JQuery Typeahead 插件调用本地 JSON 文件中的嵌套值。

我有以下使用 typeahead 插件:

$('#country_v1-query').typeahead({
    order: "desc",
    emptyTemplate: 'No result for "{{query}}"',
    source: {
        data: {
            url: ["/json/test.json", "data.country"]
        },
    },
    callback: {
        onInit: function (node) {
            console.log('Typeahead Initiated on ' + node.selector);
        },
        onSearch: function (node, query) {
            //console.log(query);
        }
    }
});

JSON 文件是:

{
        data: 
        {
            "country": 
            [
                "AfghanisTan",
                "Albania",
                "Algeria",
                "Andorra",
                "Angola",
                "Antigua and Barbuda",
                "Argentina",
                "Armenia",
                "Australia",
                "Austria",
                "Azerbaijan"
            ]
        }
}

我想从数组中检索“国家”值。有更好的 Jquery 专业知识的人能否突出显示执行此操作的最佳方法?

问候, J

【问题讨论】:

  • 我想不出任何其他方式来做到这一点。显然“data.country”应该带回建议的值?
  • 您只需要修正您编写 json 的方式,以及从数据对象中取出“url”。我给你写了详细的答案。

标签: javascript jquery json typeahead.js


【解决方案1】:

我从 data: {} 对象中取出了“url”参数并移除了 data 对象:

source: {
    url: ["/json/test.json", "data.country"]
},

您还必须在 json 中的“数据”对象周围添加双引号:

"data": { ... }

我把所有的东西放在下面,以防你仍然有麻烦。

完整的jquery代码:

$('#country_v1-query').typeahead({
    order: "desc",
    emptyTemplate: 'No result for "{{query}}"',
    source: {
        url: ["/json/test.json", "data.country"]
    },
    callback: {
        onInit: function (node) {
            console.log('Typeahead Initiated on ' + node.selector);
        },
        onSearch: function (node, query) {
            //console.log(query);
        }
    }
});

完整的 JSON 代码:

{
    "data":
    {
        "country": 
        [
            "AfghanisTan",
            "Albania",
            "Algeria",
            "Andorra",
            "Angola",
            "Antigua and Barbuda",
            "Argentina",
            "Armenia",
            "Australia",
            "Austria",
            "Azerbaijan"
        ]
    }
}

【讨论】:

    猜你喜欢
    • 2015-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-24
    相关资源
    最近更新 更多