尝试访问json对象时出现“无法找到变量”错误

时间:2016-01-08 17:30:51

标签: javascript jquery json

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

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

我要做的是在第一个选择菜单中,一旦用户选择了县,第二个选择菜单就会更新来自son对象的值。目前我收到一个'找不到变量'的错误,我无法理解为什么。数据阵列由于某种原因不可用吗?

<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>

1 个答案:

答案 0 :(得分:3)

此行中的数据不在范围内

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

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

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