2013-04-24 71 views
2

文件 「zip.json」: { 「zip11111」: 「City1」, 「zip99999」: 「城2」 }如何正確返回並顯示json數據和getJSON?

的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。這也可能是很簡單的,但我不能看到它... ...

+0

只需使用'console.log(data)'查看返回的具體內容,然後根據該對象進行編寫 – SpYk3HH 2013-04-24 20:35:37

+0

我會添加括號。同樣謝謝,雖然! – user2317194 2013-04-24 20:52:30

回答

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的關鍵。

+0

作品!我理解這個解釋。非常感謝你! – user2317194 2013-04-24 20:47:22

+0

很高興幫助! – 2013-04-24 20:48:57

+1

的確如此!你的回答速度也讓我印象深刻。 – user2317194 2013-04-24 20:49:58