Javascript 访问JSON对象详细信息

Javascript 访问JSON对象详细信息,javascript,json,Javascript,Json,我有一个简单的表单,可以提交所选位置地址的详细信息。在提交之前,我希望允许用户预览将要发送的地址。地址存储在JSON对象中。我有以下代码: HTML: 天安2号 天安3号 JS: 函数showAddress() { var-JSONAddress= [ {“id”:“天安号”, “现场1”:“96,3公丹1 ro”, “第二战场”:“天安寺赛布谷”, “现场3”:“韩国忠清南道,31093” }, { “id”:“天安3号”, “现场1”:“80,3公丹6 ro,”, “第二战场”:“天

我有一个简单的表单,可以提交所选位置地址的详细信息。在提交之前,我希望允许用户预览将要发送的地址。地址存储在JSON对象中。我有以下代码:

HTML:


天安2号
天安3号

JS:


函数showAddress()
{
var-JSONAddress=
[
{“id”:“天安号”,
“现场1”:“96,3公丹1 ro”,
“第二战场”:“天安寺赛布谷”,
“现场3”:“韩国忠清南道,31093”
},
{
“id”:“天安3号”,
“现场1”:“80,3公丹6 ro,”,
“第二战场”:“天安寺城步”,
“现场3”:“韩国忠清南道,31085”
}
];
var e=document.getElementById(“selectAddress”);
var selectedAddress=e.options[e.selectedIndex].value;

对于(var i;i而言,问题在于
for
循环的变量
i
不是初始化到0
函数showAddress()
{
var-JSONAddress=
[
{“id”:“天安号”,
“现场1”:“96,3公丹1 ro”,
“第二战场”:“天安寺赛布谷”,
“现场3”:“韩国忠清南道,31093”
},
{
“id”:“天安3号”,
“现场1”:“80,3公丹6 ro,”,
“第二战场”:“天安寺城步”,
“现场3”:“韩国忠清南道,31085”
}
];
var e=document.getElementById(“selectAddress”);
var selectedAddress=e.options[e.selectedIndex].value;

对于(var i=0;i首先,您没有将循环中的
var i
初始化为
0

其次,(在小提琴中)您使用了
getElementById
——它应该是
document.getElementById

第三,(在你的小提琴中)有
json.JSONAddress
——它应该只有
JSONAddress


<html>
<form action="something.asp" >
<select id="selectAddress">
   <option value="Cheonan2">Cheonan 2</option>
   <option value="Cheonan3">Cheonan 3</option>
</select>
<input type="submit"/>
</form>
<input type="button" value="Display addresses" onClick="showAddress()"/><br>

<span id="addressField1"></span>
<span id="addressField2"></span>
<span id="addressField3"></span>
</html>
<script>
function showAddress()
{
    var JSONAddress =
        [
            {           "id":"Cheonan2",
                        "Field1": "96, 3Gongdan1-ro",
                        "Field2": "Seobuk-gu, Cheonan-si",
                        "Field3": "Chungcheongnam-do, 31093, Korea"
            },

            {
                        "id":"Cheonan3",
                        "Field1": "80, 3Gongdan6-ro,",
                        "Field2": "Seobuk-gu, Cheonan-si,",
                        "Field3": "Chungcheongnam-do, 31085, Korea"
            }

        ];


    var e=document.getElementById("selectAddress");
    var selectedAddress = e.options[e.selectedIndex].value;

    for (var i;i<JSONAddress.length;i++){
        if (JSONAddress[i].id===selectedAddress){
                                    document.getElementById('addressField1').innerHTML=JSONAddress[i].Field1;
                document.getElementById('addressField2').innerHTML=JSONAddress[i].Field2;
                document.getElementById('addressField3').innerHTML=JSONAddress[i].Field3;

            }

        }

}
</script>