如何使用getJSON正确返回和显示json数据?

时间:2013-04-24 20:29:00

标签: jquery json getjson postal-code

文件“zip.json”:     {     “zip11111”:“City1”,     “zip99999”:“City2”     }

javascript:

jQuery(document).ready(function() {
$("#textbox1zip").change(function() {
    $.getJSON('zip.json', function(data) {

    /* each of the following code blocks don't work when exchanged for each other:

    1 zipcode = "zip" + $("#textbox1zip").val();
    * $('#textbox2city').val( data.zipcode ); -----> call silently dropped

    2 zipcode = 'zip99999';
    * $('#textbox2city').val( data.zipcode ); -----> call silently dropped

    3 zipcode = "zip" + $("#textbox1zip").val();
    * alert( data.zipcode ); -----> returns 'undefined'
    */

    /* but each of these blocks here works:
    4 $('#textbox2city').val( data.zip99999 ); ------> ok

    5 alert( data.zip99999 ); -----> ok

    6 zipcode = 'zip99999';
    * $('#textbox2city').val( zipcode ); ------> ok

    7 zipcode = "zip" + $("#textbox1zip").val();
    * $('#textbox2city').val( zipcode ); ------> ok
    */
    });
});
});

我希望从textbox1zip获取的值将“zip.json”中的相应值返回到textbox2city中。我想使用getJSON。它可能很简单,但我看不到它......

1 个答案:

答案 0 :(得分:3)

试试这个:

var zipcode = 'zip99999';   // or 'zip11111'
$('#textbox2city').val( data[zipcode] );

var zipcode = "zip" + $("#textbox1zip").val();
$('#textbox2city').val( data[zipcode] );

现在,这个alert( data.zipcode ); -----> returns 'undefined'

这是因为json对象只有两个键zip11111& zip99999。因此,data.zip11111data.zip99999有效,而data.zipcode没有,因为没有名称为zipcode的密钥。