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

如何在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条)

报告相同问题?

悬赏问题

  • ¥15 fluent的在模拟压强时使用希望得到一些建议
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退