我正在使用以下代码对返回我想要的信息的数据库运行查询。我现在想将其显示在屏幕上。
function display(parsed) {
article = document.getElementById("homeArticle");
item = '<p>Something should go here</p>';
for (var i = 0; i < parsed.length; i++) {
var item = parsed[i];
var name = item.P_NAME;
var description = item.P_DESCRIPTION;
var price = item.P_PRICE;
// next I add to the string that we want to place on the page
item += '<section id="homePageSection"> <p>Name:' + name + '</p><p>Description:' + description + '</p><p>Price:' + price + '</p></section>';
};
article.innerHTML = item;
}
function getItems() {
var xhr = new XMLHttpRequest();
xhr.onload = function() {
console.log(this.response)
var parsed = JSON.parse(this.responseText);
display(parsed.rows);
};
xhr.open("GET", "displayData.php");
xhr.send();
}
window.addEventListener("load", getItems);
但是,这不会在屏幕上显示结果。我使用 console.log 来查看是否是 getItems 函数不起作用,但这会记录我想要的信息,所以我得到了正确的信息,我只需要它显示在屏幕上,但我不知道为什么它不工作?
下面是控制台中记录的内容。
{"rows":[{"P_ID":"1","P_NAME":"Iphone 6","P_DESCRIPTION":"the latest iphone","P_PRICE":"300"},{"P_ID":"2","P_NAME":"Ipad Mini","P_DESCRIPTION":"the latest and smallest ipad","P_PRICE":"199.99"},{"P_ID":"3","P_NAME":"MacBook Pro","P_DESCRIPTION":"the macbook pro","P_PRICE":"999"},{"P_ID":"4","P_NAME":"Ipad Cover","P_DESCRIPTION":"a cover for ipad","P_PRICE":"30"},{"P_ID":"8","P_NAME":"Iphone 5c","P_DESCRIPTION":"the iphone 5c","P_PRICE":"150"},{"P_ID":"9","P_NAME":"Windows 8 laptop","P_DESCRIPTION":"a laptop with windows 8","P_PRICE":"250"}]}
最佳答案
看起来您正在将原始响应文本而不是解析的对象传递给函数。
应该是这样的:
xhr.onload = function() {
console.log(this.response)
var parsed = JSON.parse(this.responseText);
display(parsed); // <-----
};
您的 display
函数还存在几个问题:
// v----- this said parsed instead of results
function display(results) {
article = document.getElementById("homeArticle");
item = '<p>Something should go here</p>';
for (var i = 0; i < results.length; i++) {
var item = results[i];
var name = item.P_NAME;
var description = item.P_DESCRIPTION;
var price = item.P_PRICE;
// next I add to the string that we want to place on the page
item += '<section id="homePageSection"> <p>Name:' + name + '</p><p>Description:' + description + '</p><p>Price:' + price + '</p></section>';
}
article.innerHTML = item; // needs to be innerHTML
}
编辑:您的数组位于名为 rows
的属性上,因此您需要在将其传递给 display()
时访问此属性:
display(parsed.rows);
或者在您的display()
函数中访问它:
function display(response) {
var results = response.rows;
...
}
关于javascript - 结果未显示在屏幕上,但我没有收到控制台错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29038292/