javascript - 尝试访问 json 对象时出现 'Cannot find variable' 错误

标签 javascript jquery json

希望有人能帮助我。下面的 JS 加载 JSON 文件并将县解析为选择菜单。它还会删除重复项。现在,在 JSON feed 中,每个项目都有这样的内容:

{
   "County":"Antrim",
   "Town":"Antrim Town",
   "Restaurant":"Diane's Restaurant & Pizzeria"
}

我想做的是在第一个选择菜单中,一旦用户选择了县,第二个选择菜单就会使用子对象中的值进行更新。目前我收到“找不到变量”错误,但我不知道原因。数据数组是否由于某种原因不可用?

<script type="text/JavaScript">
    $(document).ready(function(){
    //get a reference to the select elements
    var county = $('#county');
    var town = $('#town');
    var restaurant = $('#restaurant');

    //request the JSON data and parse into the select element
    $.getJSON('rai.json', function(data){
        console.log(data);

        //clear the current content of the select
        $('#county').html('');
        $('#county').append('<option>Please select county</option>');

        $('#county').html('');
        $('#town').append('<option>Please select town</option>');

        $('#restaurant').html('');
        $('#restaurant').append('<option>Please select restaurant</option>');

        //iterate over the data and append a select option
        $.each(data.irishtowns, function(key, val) {
            county.append('<option id="' + val.County + '">' + val.County+ '</option>');
        });

        var a = new Array();
        $('#county').children("option").each(function(x){
            test = false;
            b = a[x] = $(this).text();
            for (i=0;i<a.length-1;i++){
                if (b ==a[i]) test =true;
            }
            if (test) $(this).remove();
        });
    });

    $( "#county" ).change(function() {
        var myCounty = $(this).val();
        console.log(myCounty);
        $.each(data.irishtowns, function(key, val) {
            if (val.Town === myCounty) {
                town.append('<option id="' + val.Town + '">' + val.Town + '</option>');
            }
        });
    });
});
</script>

最佳答案

数据不在本行范围内

$.each(data.irishtowns, function(key, val) {

您可以将其移至回调中,或使用全局变量来提供访问:即在回调中包含一行 countries = data ,然后是

$.each(countries.irishtowns, function(key, val) {

关于javascript - 尝试访问 json 对象时出现 'Cannot find variable' 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34682776/

相关文章:

javascript - 找不到为什么要列出最近 12 个月的这个 js/jQuery 生成 "undefined"警告

javascript - react : Javascript filter search not working on backspace

javascript - 我可以在这里使用 for 循环而不是编写一百行代码吗?

javascript - jQuery SVG Line stroke-linejoin(编辑 : SVG markers)

javascript - jQuery UI 选项卡 : Load link in tab/Reload entire page

javascript - 通过ajax提交表单并通过JSON从servlet回复,无需刷新页面

c# - 将 Tuple<string,string> 列表输出为 JSON 对象

javascript - 使用 Qlik Engine JSON API 导出可视化数据

javascript - Nodejs 应用程序抛出不能使用 body-parser 中间件发布/用户

javascript - js私有(private)变量赋值