doulu8446
2015-04-02 22:03
浏览 347
已采纳

如何在html页面中显示JSON对象列表

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

Here is what I have

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 is below

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 returns the following from a database. They have been 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"}

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":"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条)

相关推荐 更多相似问题