【发布时间】:2020-07-25 08:34:58
【问题描述】:
我希望得到社区的一些帮助。我试图了解如何编写代码以从 json 文件读取到下拉列表。我正在使用 node.js 来运行应用程序。
我正在从“http://localhost:4300/location”访问 json 对象: { "1": "82 North Wall Quay, Dublin 1", "2": "Eastwall Wall Road, Dublin 3", "3": "4 Grand Canal Square, Dublin 2" }
<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;
}
谢谢
【问题讨论】:
-
显示您正在使用的数据。例如。
.forEach()方法仅适用于数组... -
你的 jsonData 是 json 数组还是 json 对象?显示 jsonData 的内容。
-
{ "1": "82 North Wall Quay, Dublin 1", "2": "Eastwall Wall Road, Dublin 3", "3": "4 Grand Canal Square, Dublin 2" }
-
请在帖子中包含所有相关信息。
标签: javascript node.js json ajax dropdown