2015-04-02 22:03
浏览 347


NOTE: Need to implement this without the use of jQuery or any other open source code.

Here is what I have


<!DOCTYPE html>
<head lang="en">
    <meta charset="UTF-8">
    <script src="js.js"></script>
<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>

js.js is below

var getProducts = function(){

console.log("Getting Products...");
var success = function() {
            var product = JSON.parse(xhr.responseText);
            document.getElementById("name").innerHTML =;
            document.getElementById("desc").innerHTML = product.desc;
            document.getElementById("cost").innerHTML = product.cost;
            document.getElementById("stock").innerHTML = product.stock;

xhr = new XMLHttpRequest();"GET", "back.php");
xhr.addEventListener("load", success);

window.addEventListener("load", getProducts);

back.php returns the following from a database. They have been json_encoded:

{"name":"soot","desc":"soooottty black","cost":"980.00","stock":"10"}
{"name":"baby","desc":"chucky doll","cost":"7.92","stock":"34"}

I need to display these objects onto the html page. I know I need to implement a for loop however, no matter whatever I try, a parse error for JSON comes up.

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);

Would much appreciate it if someone could help me understand how to display all the JSON objects onto the html page.

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • du229908 2015-04-02 22:11

    Your JSON is invalid. You need to put the objects in an array, and separate them by commas.

    {"name":"soot","desc":"soooottty black","cost":"980.00","stock":"10"},
    {"name":"baby","desc":"chucky doll","cost":"7.92","stock":"34"},
    解决 无用
    打赏 举报
  • 查看更多回答(1条)

相关推荐 更多相似问题