我创建了一个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格式的结果?
答案 0 :(得分: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.
}