douchenchepan6465 2017-05-20 07:20
浏览 32
已采纳

如何在Javascript中使用PHP中的JSON数据(数组)

I would like to retrieve each element inside of this.responseText, and put them in my HTML on Javascript. Is there something wrong in my code? I hope my code helps you to understand my question. Thanks. (p.s. the html code is provided, and so I cannot use jquery.)

an example of this.responseText is below; (By using alert, I got that)

{"name":"Hermione Grainger","number":"4","review":"Not as good as the NEXT book in the series, but hilarious and satisfying."}{"name":"Ronald Drumpf","number":"1","review":"Feminist propaganda!"}{"name":"Brienne of Tarth","number":"5","review":"Alanna is my best friend."}

And my java script is below;

function bookReview(){
    var reviews = JSON.parse(this.responseText);
    for(var i=0; i<reviews.length; i++){
        var name = document.createElement("h3");
        var text = document.createElement("p");
        name.innerHTML = reviews[i].name + reviews[i].number;
        text.innerHTML = reviews[i].review;

        document.getElementById("reviews").appendChild(name);
        document.getElementById("reviews").appendChild(text);
    }
}

or is there something wrong in my PHP code??

$path = "books/$book/";
review(glob($path . "review" . "*" . ".txt"));

function review($reviews) {
    foreach ($reviews as $each) {
        $review = file($each, FILE_IGNORE_NEW_LINES);
        $output = array (
            "name" => $review[0],
            "number" => $review[1],
            "review" => $review[2]
            );
        header("Content-type: application/json");
        print(json_encode($output));
    }
}
  • 写回答

2条回答 默认 最新

  • douwendu2460 2017-05-20 07:23
    关注

    This doesnt look like valid JSON, should be like '[{},{},{}]'. If you want you can use a JSON validator, e.g. http://json-validator.com/.

    To generate the JSON array properly you can do:

    $array = [];
    foreach ($reviews as $each) {
        $review = file($each, FILE_IGNORE_NEW_LINES);
        $output = array (
            "name" => $review[0],
            "number" => $review[1],
            "review" => $review[2]
            );
        array_push($array,$review);
    }
    print(json_encode($array));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 matlab计算中误差
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊