如何从AJAX中的silex控制器接收JSON数据

时间:2017-04-12 16:38:28

标签: php json ajax silex

当我试图从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时,我不知道为什么会出现问题。

1 个答案:

答案 0 :(得分: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);
}