JSON.parse没有运行

时间:2018-04-02 20:40:11

标签: javascript php json

我正在尝试从PHP获取JSON对象到Javascript。目前我的Javascript代码已经有了这个:

function GetEvents()
{   
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange  = function()
    {
        if (this.readyState == 4 && this.status == 200) 
        {
            var eventObject = JSON.parse(this.responseText);
            alert("Hello");
        }
    }
    xmlhttp.open("GET", "php/includes/GetEvents.php", true);
    xmlhttp.send();
}

与之交谈的PHP是:

<?php
include_once 'dbConnect.php';
include_once 'config.php';

class Event
{
     public $eventName;
     public $eventStart;
     public $eventEnd;
}

$prep = "SELECT eventName, eventStart, eventEnd FROM Events ORDER BY eventStart 
DESC";
$statement = $link->prepare($prep);//Prepare Selection from the Database
if($statement)
{
    //Executes SELECT;
    $statement->execute();

    $result = $statement->get_result();
    if ($result->num_rows > 0) 
    {
        $event = new Event;
        while($row = $result->fetch_assoc())
        {
            $event->eventName = $row['eventName'];
            $event->eventStart = $row['eventStart'];
            $event->eventEnd = $row['eventEnd'];

            echo json_encode($event); //Returns the Event object as a JSON      
        }   
    }
}
?>

我遇到的问题是我的javascript代码中的JSON.parse部分似乎没有实际工作,或者至少运行时考虑到它下面的任何代码都没有运行,而它上面的代码却没有。所以我很确定这是因为JSON.parse有错误,但我不知道问题是什么。

任何帮助?

1 个答案:

答案 0 :(得分:3)

您在循环的每次迭代中echo一个JSON字符串。所以最后的字符串不是有效的JSON字符串。您可以创建一个数组,以存储数据,并在进程结束时回显JSON字符串:

$data = []; // create an array
$statement = $link->prepare($prep);//Prepare Selection from the Database
if($statement)
{
    //Executes SELECT;
    $statement->execute();

    $result = $statement->get_result();
    if ($result->num_rows > 0) 
    {
        $event = new Event;
        while($row = $result->fetch_assoc())
        {
            $event->eventName = $row['eventName'];
            $event->eventStart = $row['eventStart'];
            $event->eventEnd = $row['eventEnd'];

            $data[] = $event; // store data into array
        }   
    }
}
echo json_encode($data); // Returns ALL events as a JSON