doulu8446 2015-04-02 22:03
浏览 392


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"},
    本回答被题主选为最佳回答 , 对您是否有帮助呢?



  • ¥15 Mapreduce是正常的,在运行其他jar包时并没有任何问题,只是在做LogCount.jar 时出的问题。如图所示
  • ¥15 ImportError: DLL load failed while importing _iterative: 找不到指定的模块。
  • ¥15 如何通过交互分析得出某高危患者对放疗获益更多
  • ¥15 相关性分析中,p<0.05, r=0.29,怎么评价相关性呢
  • ¥15 docker部署Mongodb后输入命令报错?
  • ¥15 将下列流程图转变成python程序代码
  • ¥15 我需要全国每个城市的最新小区名字等数据。
  • ¥15 开发一个小区生态的小程序
  • ¥15 如何解决Excel中dependent dropdown list 的问题
  • ¥15 MddBootstrapInitialize2失败