来自JSON对象的读取元素失败

时间:2014-07-29 08:21:38

标签: javascript jquery json

我正在尝试使用JavaScript和jQuery从JSON对象中读取内容。 但我不断抛出“代码”未设置的异常。我想要做的是从字符串中读取国家/地区代码,并根据字符串的内容预填充输入字段。

这是我的代码:

<input type="text" name="country">
<script>
    $(document).ready(function () {
    var countryData = [{
        "id": 23,
        "code": "DK",
        "country": "Danmark",
        "phone_phoneext": "+45"
    }, {
        "id": 24,
        "code": "SE",
        "country": "Sverige",
        "phone_phoneext": "+46"
    }, {
        "id": 25,
        "code": "NO",
        "country": "Norge",
        "phone_phoneext": "+47"
    }];

    var countryCookie = "DK"; //Will be read from a cookie later 

    function getCountryByCookie(countryCode) {
        return countryData.filter(

        function (countryData) {
            return countryData.code == code
        });
    }

    try {
        var foundCountryCookie = getCountryByCookie(countryCookie);
        $("input[name=country]").val(foundCountryCookie[0].country);
    } catch (e) {
        console.log(e);
    }
});
</script>

1 个答案:

答案 0 :(得分:4)

那是因为您从未声明或设置变量code

function getCountryByCookie(countryCode) {
     return countryData.filter(
         function(countryData){return countryData.code == countryCode} //countryCode instead of just code
     );
}