简体   繁体   English

如何在Symfony2中将视图文件呈现为json对象以进行Ajax请求

[英]How to render a view file as json object in symfony2 for ajax requests

I have an action for login process. 我有一个登录过程的动作。 Now I want to use the same action for normal login process and for ajax requests also. 现在,我想对正常的登录过程和ajax请求使用相同的操作。

        /**
         * @Route("/sponsor/login", name="sponsor_login", options={"expose"=true})
         * @Template("SponsorBundle::login.html.twig")
         * @return array
         */
         public function loginAction()
         {}

I want this action to render different view files for xmlhttp request and for normal http request.How do i do that? 我希望此操作为xmlhttp请求和普通的http请求呈现不同的视图文件。我该怎么做? and I want to pass view file in a json object 我想在json对象中传递视图文件

You can do this: 你可以这样做:

return $this->getRequest()->isXmlHttpRequest()
 ? $this->render(.... "form.html.twig" ....)
 : $this->render(... full page that will include the form ...) ;

or 要么

if ($this->getRequest()->isXmlHttpRequest()){
  $template = "form.html.twig" ;
  $params = ....
} else {
  $template = "login.html.twig" ;
  $params = ....
}

return $this->render($template, $params) ;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM