注意:需要在不使用jQuery或任何其他开源代码的情况下实现此目的。
这就是我所拥有的
HTML:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Model</title>
<script src="js.js"></script>
</head>
<body>
<h1>Browse all our products below:</h1>
Name: <span id="name"></span><br>
Desc: <span id="desc"></span><br>
Cost: <span id="cost"></span><br>
Stock: <span id="stock"></span>
</body>
</html>
js.js低于
var getProducts = function(){
console.log("Getting Products...");
var success = function() {
var product = JSON.parse(xhr.responseText);
console.log(product);
document.getElementById("name").innerHTML = product.name;
document.getElementById("desc").innerHTML = product.desc;
document.getElementById("cost").innerHTML = product.cost;
document.getElementById("stock").innerHTML = product.stock;
}
};
xhr = new XMLHttpRequest();
xhr.open("GET", "back.php");
xhr.addEventListener("load", success);
xhr.send();
};
window.addEventListener("load", getProducts);
back.php从数据库返回以下内容。他们一直是json_encoded:
{"name":"TESTPRODUCT","desc":"TESTIN12356879CEWBLABHDSB","cost":"123.45","stock":"6"}
{"name":"soot","desc":"soooottty black","cost":"980.00","stock":"10"}
{"name":"baby","desc":"chucky doll","cost":"7.92","stock":"34"}
{"name":"bob","desc":"fydrtsfxgcvnb","cost":"3546.00","stock":"978"}
{"name":"bolly","desc":"ball","cost":"77.00","stock":"89"}
我需要在html页面上显示这些对象。我知道我需要实现一个for循环,但无论我尝试什么,都会出现JSON的解析错误。
SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at
line 1 column 86 of the JSON data
var product = JSON.parse(xhr.responseText);
如果有人能帮我理解如何在html页面上显示所有JSON对象,我将不胜感激。
答案 0 :(得分:0)
您的JSON无效。您需要将对象放在数组中,并用逗号分隔。
[{"name":"TESTPRODUCT","desc":"TESTIN12356879CEWBLABHDSB","cost":"123.45","stock":"6"},
{"name":"soot","desc":"soooottty black","cost":"980.00","stock":"10"},
{"name":"baby","desc":"chucky doll","cost":"7.92","stock":"34"},
{"name":"bob","desc":"fydrtsfxgcvnb","cost":"3546.00","stock":"978"},
{"name":"bolly","desc":"ball","cost":"77.00","stock":"89"}]
答案 1 :(得分:0)
以下是使用开源项目jinqJs的示例 此示例还使用了jQuery。
//data can also be a string to a url that returns JSON
jinqJs().from(data).select(function(row) {
$('#items')
.append($("<option></option>")
.attr("value",row.nam)
.text(row.desc));
}
);