[英]How to receive JSON data from silex controller in AJAX
當我嘗試從AJAX中的PHP文件接收JSON數據時,一切正常:
test.php的
<?php
header("Content-Type: application/json; charset=UTF-8");
$pdo = new PDO('mysql:host=localhost;dbname=database', 'root', '');
$stmt = $pdo->prepare("SELECT id, name FROM table");
$stmt->execute();
$stmt = $stmt->fetchAll(PDO::FETCH_CLASS);
echo json_encode($stmt);
?>
main.js
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myObj = JSON.parse(this.responseText);
console.log(myObj);
document.getElementById("par").innerHTML = myObj[4].id + " " + myObj[4].tag1;
}
};
xmlhttp.open("GET", "http://localhost/project/app/models/Test.php", true);
xmlhttp.send();
但是,當我嘗試從silex控制器接收JSON時:
Ajax.php
namespace AI\models;
use Silex\Application;
use Silex\Api\ControllerProviderInterface;
class Ajax implements ControllerProviderInterface
{
public function connect(Application $app){
$controllers = $app['controllers_factory'];
$controllers->get('/', 'AI\models\Ajax::home');
return $controllers;
}
public function home(Application $app){
header("Content-Type: application/json; charset=UTF-8");
$result = $app['db']->prepare("SELECT id, name FROM table");
$result->execute();
$result = $result->fetchAll(\PDO::FETCH_CLASS, \AI\models\Ajax::class);
echo json_encode($result);
return $app['twig']->render('ajax.twig');
}
}
main.js
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myObj = JSON.parse(this.responseText);
console.log(myObj);
document.getElementById("par").innerHTML = myObj[4].id;
}
};
xmlhttp.open("GET", "http://localhost/project/app/models/Ajax.php", true);
xmlhttp.send();
我在控制台中收到一個錯誤:
Uncaught SyntaxError: Unexpected token < in JSON at position 0
at JSON.parse (<anonymous>)
at XMLHttpRequest.xmlhttp.onreadystatechange (main.js:4)
xmlhttp.onreadystatechange @ main.js:4
我不知道為什么嘗試從類接收JSON時會出現問題。
如果要返回json,則應使用JsonResponse對象 。 另外,您絕對不希望像現在那樣渲染模板,只想要json數據,為什么要渲染模板?
您可以按照先前鏈接的文檔進行操作,但是幸運的是, Silex具有用於返回json數據的輔助方法 ,您甚至無需直接使用JsonResponse:
<?php
public function home(Application $app){
$result = $app['db']->prepare("SELECT id, name FROM table");
$result->execute();
$result = $result->fetchAll(\PDO::FETCH_CLASS, \AI\models\Ajax::class);
return $app->json($result);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.