【发布时间】:2019-01-18 19:48:01
【问题描述】:
我正在尝试制作一个函数来获取服务器响应 (JSON) 并在不使用 JQuery 的情况下在网页上的列表中显示来自 JSON 的信息。这怎么可能?
filterGet: function () {
var ajax = new XMLHttpRequest();
ajax.onreadystatechange=function() {
if (ajax.readyState==4 && ajax.status==200)
{
var ul = document.getElementById("results");
while(ul.firstChild){
ul.removeChild(ul.firstChild);
}
//i am trying to get the JSON response from the server
var array = ajax.response;
var i;
for(i=0;array.length;i++){
var latitudeForm = array[i].Latitude;
var longitudeForm = array[i].Longitude;
var nameForm = array[i].TagName;
var hashForm = array[i].HashName;
var newli = document.createElement('li');
newli.className = "tagListElements";
newli.innerText = nameForm + "(" + latitudeForm + ","
+ longitudeForm + ")" + hashForm;
ul.appendChild(newli);
}
}
}
ajax.open('GET', "/test1" , true);
ajax.setRequestHeader("Content-Type", "application/json");
ajax.send();
}
使用 Postman,我得到以下“GET”正文:
[
{
"Latitude": "45.01379",
"Longitude": "4.390071",
"TagName": "Casel",
"HashName": "#begaiburje"
},
{
"Latitude": "59.01379",
"Longitude": "7.390071",
"TagName": "Casel",
"HashName": "#ne"
}
]
The output is just for presentation purposes
简单地说,我想在不使用 JQuery 的情况下实现以下目标:
var main = function() {
"use strict";
var addTodosToList = function(todos) {
var todolist = document.getElementById("todo-list");
for (var key in todos) {
var li = document.createElement("li");
li.innerHTML = "TODO: " + todos[key].message;
todolist.appendChild(li);
}
};
$.getJSON("todos", addTodosToList);
}
$(main);
【问题讨论】:
-
您的代码中现在没有 jQuery,当前的输出是什么?您遇到的具体问题是什么?
-
您是否调试过
ajax变量上可用的属性。数据可能不在response中,可能在responseText中,我忘记了。但无论如何,它很可能仍然是一个字符串,您需要使用JSON.parse()将其转换为数组。 -
@Taplar 谢谢!有效!你拯救了这一天!
标签: javascript node.js ajax express