在Symfony2中发出Ajax请求

时间:2016-05-28 19:55:14

标签: ajax symfony

我的问题是该方法没有返回真实的结果。      我想测试输入的电子邮件是否存在于我的实体中。

这是控制器:

public function verificationAction(Request $request)
{
    if ($this->container->get('request')->isXmlHttpRequest()) {
        $email=$request->request->get('email');

        $em=$this->getDoctrine()->getEntityManager();
        $resp= $em->getRepository("CMSiteBundle:Prospect")->findBy(array('email'=>$email));
        $response =new Response(json_encode($resp));
        $response->headers->set('Content-Type', 'application/json');
        return $response;
    }
} 

1 个答案:

答案 0 :(得分:0)

你可以尝试一个老把戏。因为在Symfony Controller Actions中,你必须返回一个Response,为什么不假装DEAD RESPONSE,如下所示:

    <?php

        class ABCController {

            public function verificationAction(Request $request) {
                if ($this->container->get('request')->isXmlHttpRequest()) {
                    $email = $request->request->get('email');

                    $em       = $this->getDoctrine()->getEntityManager();
                    $resp     = $em->getRepository("CMSiteBundle:Prospect")
                                   ->findBy(array('email' => $email));
                    //$response = new Response(json_encode($resp));
                    //$response->headers->set('Content-Type', 'application/json');
                    // THE TRICK IS THAT DIE RUNS FIRST 
                    // THUS SENDS YOUR RESPONSE YOU THEREBY
                    // STOPPING THE RETURN FROM FIRING... ;-)
                    return die(json_encode($resp));
                }
            }
        }

也许这个非常古老的伎俩仍然适合你...... ;-)