简体   繁体   中英

Pass JSON formatted data from PHP script to AJAX

I have a created a PHP class that retrieves all the data from a database and gets back the results in JSON format:

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);
}

then an object of the class calls this method and is able to successfully do exactly that:

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

$dbh->getCategories();

How do I pass this data to my AJAX script so that it can manipulate the JSON-formatted results?

This should do it in your javascript:

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

And you need to be echo-ing your json encoded data in the php script

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;
}

I would actually throw that into it's own thing for re-use later on too:

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.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM