【问题标题】:Pulling external JSON file into a javascript variable using jQuery使用 jQuery 将外部 JSON 文件拉入 javascript 变量
【发布时间】:2013-03-21 03:38:42
【问题描述】:

我一直在构建 Twitter Bootstrap Typeahead 插件的一些示例代码。

在脚本的早期开发版本中,我包含了以下内容,几乎直接从示例中提取,并带有一些完美运行的自定义;

$('.building_selector').typeahead({
    source: function (query, process) {
        buildings = [];
        map = {};   
        var data = [{"buildingNumber":"1","buildingDescription":"Building One"},{"buildingNumber":"2","buildingDescription":"Building Two"},{"buildingNumber":"3","buildingDescription":"Building Three"}];
        $.each(data, function (i, building) {
            map[building.buildingDescription] = building;
            buildings.push(building.buildingDescription);
        });
        process(buildings);
},
updater: function (item) {
    selectedBuilding = map[item].buildingNumber;
    return item;    
},
});

实际上,当我将选项数组直接写入代码时,这并没有多大用处,因此我一直在研究读取写入 JSON 的外部文件。我创建了一个文件,只包含如下数组;

[{"buildingNumber":"1","buildingDescription":"Building One"},
{"buildingNumber":"2","buildingDescription":"Building Two"},
{"buildingNumber":"3","buildingDescription":"Building Three"}]

我现在尝试更新 Javascript 以包含加载远程文件的代码。我可以验证文件是否存在并且位于正确的相对位置。

$('.building_selector').typeahead({
    source: function (query, process) {
        buildings = [];
        map = {};
        var data = function () {
            $.ajax({
                'async': false,
                'global': false,
                'url': "../json/buildings",
                'dataType': "json",
                'success': function (result) {
                    data = result;
                }
             });
            return data;
        }(); 

    $.each(data, function (i, building) {
        map[building.buildingDescription] = building;
        buildings.push(building.buildingDescription);
    });

process(buildings);
    },

updater: function (item) {
    selectedBuilding = map[item].buildingNumber;
    return item;    
},
});

在运行页面时,所有元素似乎都按预期工作,并且控制台中不会出现任何内容,直到您在文本字段内单击并正在输入。每次按键后,什么都没有发生,但控制台中会产生以下内容;

未捕获的类型错误:无法读取未定义 [jquery.min.js:3] 的属性“长度”

任何尝试解决此问题的想法/想法/起点将不胜感激!

【问题讨论】:

  • async': false, 不好......并且已弃用。移动代码,使process(buildings);success 回调中。不确定是否可以接受,但如果 json 文件是静态的,可以将其包含在页面的脚本标记中并使用 AJAX 跳过。只需在数组前面添加var myBuildingData= 并在source 函数中处理该变量

标签: javascript jquery json twitter-bootstrap


【解决方案1】:

首先,我建议您使用 $.getJSON 而不是 $.ajax(您可以节省很多不必要的代码行)。 // 在此处查看 $.getJSON 文档:http://api.jquery.com/jQuery.getJSON/

其次,您必须根据其范围引用数据变量(在成功函数中调用data var时,范围已更改并且未找到data var,这就是它抛出“Cannot read 'leangth' of不明确的”)。您必须设置一个指向数据变量范围的自引用变量。

这会有所帮助:

$('.building_selector').typeahead({
    source: function (query, process) {
        var buildings = [];
        var map = {};
        var self = this; //This is a self reference to use in the nested function of $.getJSON

        $.getJSON('../json/buildings', function(data){
            if ($.isArray(data)) {
                $.each(data, function (i, building) {
                    self.map[building.buildingDescription] = building;
                    self.buildings.push(building.buildingDescription);
                });
                process(self.buildings);
            }
        });
    },

    updater: function (item) {
        selectedBuilding = map[item].buildingNumber; // This won't work. I'd suggest to move the map variable as part of the top level object.
        return item;    
    }
});

【讨论】:

  • 我一直在尝试关注这一点,但无法理解最后的评论。你建议如何让它发挥作用,因为目前没有任何改进!
  • 我只是建议将 map 变量放在 building_selector 块之外。 (不要在里面声明)。
【解决方案2】:

我将添加一点解释我最后到达的点,因为它是一个很大的变化;

由于 JSON 文件的内容是动态的,但不需要在每次按键时都被调用,我决定导入一次,在 $document.ready() 中使用 $.getJSON。然后它将内容写入一个全局变量,源函数可以像以前一样加载该变量。

这是供参考的代码;

$('.building_selector').typeahead({
    source: function (query, process) {
        buildings = [];
        map = {};   
        $.each(buildinglist, function (i, building) {
            map[building.buildingDescription] = building;
            buildings.push(building.buildingDescription);
        });
        process(buildings);
    },
    updater: function (item) {
        selectedBuilding = map[item].buildingNumber;
        return item;    
    },
});
var buildingList;
$(document).ready(function() {
    $.getJSON('../json/buildings/', function(json){
        buildinglist = json;
    });
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-09
    • 1970-01-01
    • 2019-05-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多