2017-03-01 49 views
1

我需要在DIV ID = 「containerPosts」 JSON文本加載了symfonySymfony的3 JSON Peticion

在目錄網/ app_dev.php/AJAX的內容是沒有看到JSON但如果DIV是。

在目錄網/ app_dev.php顯示錯誤:「?控制器必須返回響應(空給)你忘了在你的控制器返回某處聲明」

任何想法來解決這個問題?

的appbundle \控制器\ PostController.php

<?php 

namespace AppBundle\Controller; 

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; 
use Symfony\Bundle\FrameworkBundle\Controller\Controller; 
//use BackendBundle\Entity\Post; 
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method; 
use Symfony\Component\HttpFoundation\Request; 
use Symfony\Component\HttpFoundation\JsonResponse; 

use Symfony\Component\Serializer\Serializer; 
use Symfony\Component\Serializer\Encoder\XmlEncoder; 
use Symfony\Component\Serializer\Encoder\JsonEncoder; 
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer; 

class PostController extends Controller 
{ 
    /** 
    * @Route("/ajax") 
    */ 
    public function indexAction() 
    { 
     return $this->render('AppBundle:Post:post.html.twig', array(

     )); 
    } 

    /** @Route("/ajax/posts", name="ajax_posts") 
    * @Method({"GET"}) 
    */ 
    public function postsAction(Request $request) 
    { 
     if($request->isXmlHttpRequest()) 
     { 
      $encoders = array(new JsonEncoder()); 
      $normalizers = array(new ObjectNormalizer()); 
      echo "hola2"; 
      $serializer = new Serializer($normalizers, $encoders); 

      $em = $this->getDoctrine()->getManager(); 
      $posts = $em->getRepository('BackendBundle:Post')->findAll(); 
      $response = new JsonResponse(); 
      $response->setStatusCode(200); 
      $response->setData(array(
       'response' => 'success', 
       'posts' => $serializer->serialize($posts, 'json') 
      )); 

      return $response; 
     } 
     echo "hola"; 
    } 
} 

的appbundle \資源\ CONFIG \ Post.yml(路線)

ajax_posts: 
    path: /ajax/posts 
    defaults: { _controller: AppBundle:Post:posts } 

ajax: 
    path: /ajax 
    defaults: { _controller: AppBundle:Post:index } 

的appbundle \資源\意見\後\ post.html.twig

{% block title %}AppBundle:Post:index{% endblock %} 

{% block body %} 
<h1>Welcome to the Ajax:index page</h1> 
    <div id="containerPosts"></div> 
{% endblock %} 

{% block javascripts %} 
    <script src="{{ asset("assets/js/jquery.min.js") }}"></script> 
    <script> 
     jQuery(document).ready(function($) 
     { 
      $.ajax({ 
       method: "GET", 
       url: "{{ url('ajax_posts') }}", 
       dataType: 'json', 
       success: function(data) 
       { 
        if(data.hasOwnProperty("response") && data.response === "success") 
        { 
         if(data.hasOwnProperty("posts")) 
         { 
          //http://stackoverflow.com/questions/3710204/how-to-check-if-a-string-is-a-valid-json-string-in-javascript-without-using-try/3710226 
          if (/^[\],:{}\s]*$/.test(data.posts.replace(/\\["\\\/bfnrtu]/g, '@'). 
            replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']'). 
            replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) 
          { 
           var posts = JSON.parse(data.posts); 
           if(posts.length > 0) 
           { 
            alert("aqui"); 
            var html = ""; 
            for(d in posts) 
            { 
             html += "<p>" + JSON.stringify(posts[d]) + "</p>"; 
            } 
            $("#containerPosts").append(html); 
           } 
          } 
          else 
          { 
           console.log("INVALID JSON STRING"); 
          } 
         } 
         else 
         { 
          console.log("POSTS NOT FOUND"); 
         } 
        } 
       }, 
       error: function(jqXHR, exception) 
       { 
        if(jqXHR.status === 405) 
        { 
         console.error("METHOD NOT ALLOWED!"); 
        } 
       } 
      }); 
     }); 
    </script> 
{% endblock %} 

BackendBundle \實體

<?php 

namespace AppBundle\Entity; 

use Symfony\Component\Validator\Constraints as Assert; 

/** 
* Post 
*/ 
class Post 
{ 
    /** 
    * @var int 
    */ 

    private $id; 

    /** 
    * @var title 
    */ 
    private $title; 

    /** 
    * @var body 
    */ 
    private $body; 


    /** 
    * Get id 
    * 
    * @return int 
    */ 
    public function getId() 
    { 
     return $this->id; 
    } 

    /** 
    * Set title 
    * 
    * @param string $title 
    * 
    * @return Post 
    */ 
    public function setTitle($title) 
    { 
     $this->title = $title; 

     return $this; 
    } 

    /** 
    * Get title 
    * 
    * @return string 
    */ 
    public function getTitle() 
    { 
     return $this->title; 
    } 

    /** 
    * Set body 
    * 
    * @param string $body 
    * 
    * @return Post 
    */ 
    public function setBody($body) 
    { 
     $this->body = $body; 

     return $this; 
    } 

    /** 
    * Get body 
    * 
    * @return string 
    */ 
    public function getBody() 
    { 
     return $this->body; 
    } 
} 

BackendBundle \資源\ CONFIG \原則\ Post.orm.yml

BackendBundle\Entity\Post: 
    type: entity 
    table: post 
    id: 
     id: 
      type: integer 
      nullable: false 
      options: 
       unsigned: false 
      id: true 
      generator: 
       strategy: IDENTITY 
    fields: 
     title: 
      type: string 
      nullable: true 
      length: 100 
      options: 
       fixed: false 
     body: 
      type: text 
      nullable: true 

回答

1

我懷疑,因爲你return語句是一個if語句中。你可以試試這個:

public function postsAction(Request $request) 
{ 
    $response = new JsonResponse(); 

    if($request->isXmlHttpRequest()) 
    { 
     $encoders = array(new JsonEncoder()); 
     $normalizers = array(new ObjectNormalizer()); 
     echo "hola2"; 
     $serializer = new Serializer($normalizers, $encoders); 

     $em = $this->getDoctrine()->getManager(); 
     $posts = $em->getRepository('BackendBundle:Post')->findAll(); 
     $response->setStatusCode(200); 
     $response->setData(array(
      'response' => 'success', 
      'posts' => $serializer->serialize($posts, 'json') 
     )); 
    } 

    return $response; 
} 

我不確定它是否能解決問題,但請嘗試一下。

+0

我已經修改了代碼,我已經把下面的代碼,它完美的作品。非常感謝你 – Manply

0

我已經修改了代碼,並且已經放入了下面的代碼,並且它完美地工作。非常感謝你

$response = new Response(); 

    $encoders = array(new JsonEncoder()); 

    $normalizers = array(new ObjectNormalizer()); 

    $serializer = new Serializer($normalizers, $encoders); 

    $EntityManager = $this->getDoctrine()->getManager(); 
    $client = $EntityManager->createQuery("********")->getResult(); 

    $response->setContent(json_encode(array(
     'client' => $serializer->serialize($client, 'json'), 
    ))); 

    $response->headers->set('Content-Type', 'application/json'); 
    return $response;