在下拉列表中显示json对象

问题描述 投票:0回答:2

我希望从社区中获得一些帮助。我试图了解如何编写从json文件读取到下拉列表的代码。我正在使用node.js运行该应用程序。

我正在从“ http://localhost:4300/location”访问json对象:{“ 1”:“ 82 North Wall Quay,Dublin 1”,“ 2”:“ Eastwall Wall Road,都柏林3”,“ 3”:“都柏林2大运河广场4”}

<select id="location"> </select>

function populateSelect(shop_location){

var xhttp = new XMLHttpRequest
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status==200) {

showResult(xhttp.responseText);
}
};
xhttp.open("GET", "http://localhost:4300/location", true);
xhttp.send();
}

function showResult(jsonData) {
var txt = "";
var jsonData = JSON.parse(jsonData);
jsonData.forEach (x=>{txt = txt + "<br>" +x["Title"];})

document.getElementById("location").innerHTML = txt;
}

谢谢

javascript node.js json ajax dropdown
2个回答
0
投票

您可以使用for..in循环遍历JSON对象的所有keys,并为每个对象创建一个新的option元素。

最后使用append()方法将每个新创建的option元素添加到select元素。

检查以下内容:

var jsonData = { 
  "1": "82 North Wall Quay, Dublin 1",
  "2": "Eastwall Wall Road, Dublin 3",
  "3": "4 Grand Canal Square,Dublin 2"
};

function showResult(jsonData) {
  let loc = document.getElementById("location");
  
  for(let key in jsonData) {
    let option = document.createElement("option");
    option.innerHTML = jsonData[key];
    option.value = key;
    loc.append(option);
  }
}

showResult(jsonData);
<select id="location">
</select>

0
投票
var locationRequest = new XMLHttpRequest();

locationRequest.open('GET' ,'http://localhost:4300/location')
locationRequest.onload=function(){
var locationData =JSON.parse(locationRequest.responseText);
showResult(locationData);
console.log(locationData);
}

locationRequest.send();

function showResult(locationRequest) {      
let loc = document.getElementById("location");
for(let key in locationRequest) {
let option = document.createElement("option");
option.innerHTML = locationRequest[key];
option.value = key;
loc.append(option);
}}
<select id="location" name = "location" >  </select>
© www.soinside.com 2019 - 2024. All rights reserved.