2017-04-12 72 views
0

当我试图从AJAX一切PHP文件接收JSON数据正常工作:如何从硅石控制器接收JSON数据AJAX

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

但是,当我试图从硅石控制器接收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问题来自一堂课。

回答

0

如果你要返回json,你应该使用JsonResponse Object。你也绝对不想像现在那样渲染一个模板,你只是想要json数据,为什么要渲染一个模板?

你可以按照以前链接的文档,但幸运Silex has a helper method for returning json data,你甚至都不需要使用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); 
} 
+0

我想是因为我需要轻松变量返回JSON内部控制器从URL到数据库查询,然后以JSON的形式获取数据。这就是为什么我试图渲染模板来获取使用该页面的Ajax脚本(包括树枝变量)。 – robotluke

+0

我不认为我理解你的问题。你能编辑你的问题并发布'''''ajax.twig文件'''的内容吗? – mTorres

+0

另外我的意思是,在您的AJAX调用中,您不想呈现模板,您必须呈现模板才能转到您的客户端代码(JS)进行AJAX调用的页面。这有意义吗? – mTorres

相关问题