1

我创建了一个 PHP 类,它从数据库中检索所有数据并以 JSON 格式取回结果:

public function getCategories() {
    if (!$this->isConnectionAlive()) {
        $this->getConnection();
    }

    $data = $this->dbconn->prepare("SELECT DISTINCT cat FROM regalo");
    $data->execute();
    $results=$data->fetchAll(PDO::FETCH_ASSOC);
    $json_data = json_encode($results);
}

然后类的一个对象调用这个方法并且能够成功地做到这一点:

$dbh = new DatabaseHandler('localhost', 'fakeuser', 'fakepass', 'fakedb');

$dbh->getCategories();

如何将此数据传递给我的 AJAX 脚本,以便它可以操作 JSON 格式的结果?

4

1 回答 1

3

这应该在您的 javascript 中执行:

$.get('/getCategories',null,function(response){
  console.log(response);
},"JSON");

你需要在 php 脚本中回显你的 json 编码数据

public function getCategories() {
    if (!$this->isConnectionAlive()) {
        $this->getConnection();
    }

    $data = $this->dbconn->prepare("SELECT DISTINCT cat FROM regalo");
    $data->execute();
    $results=$data->fetchAll(PDO::FETCH_ASSOC);
    $json_data = json_encode($results);
    header('Content-type: text/json');
    header('Content-type: application/json');
    echo $json_data;
}

实际上,我也会将其放入它自己的东西中以供以后重复使用:

public static function send_json_data($php_array)
{
        header('Content-type: text/json');
        header('Content-type: application/json');
        echo json_encode($php_array);
        exit(); //if you have hooks or something else that executes after output in your script, take this line out.
}
于 2013-02-17T19:17:19.603 回答