Symfony2 Ajax and Jquery

Symfony2 Ajax and Jquery

本文关键字:Jquery and Ajax Symfony2      更新时间:2023-09-26

我正在使用Symfony2和twig作为模板开发一个应用程序。我也在使用 ajax。这是我在控制器中的代码的一部分:

    public function testuaanotatuAction(Request $request)
    { 
      if ($request->isXmlHttpRequest())
      {
       return $this->forward('AnotatzaileaAnotatzaileaBundle:Page:Interpretatu');
      }
    // Some code.....
            return $this->render('AnotatzaileaAnotatzaileaBundle:Page:AnotatuInterpretazio.html.twig',
                                   array('Azpimarratu' => $Markagarria->getMarkIdent()));
}

    public function InterpretatuAction()
    {
      return $this->render('AnotatzaileaAnotatzaileaBundle:Page:FAQ.html.twig');
    }

然后这是我在AnotatuInterpretazio.html.twig'中的代码,我使用JQuery进行Ajax调用:

<script type='text/javascript'>
          $("#ButtonId").click(function () 
                             {
                               $.ajax({
                                        url: "{{ path('AnotatzaileaAnotatzaileaBundle_testuaanotatu') }}",
                                        type: "POST"
                                       });      
                         });
    </script>

正如你所看到的,我打算在这里做的是通过模板AnotatuInterpretazio.html.twig调用InterpretatuAction。然后 InterpretatuAction 将调用另一个模板。它不起作用,知道吗?

您需要

在代码中使用.success函数。如果你不这样做,什么都不会发生

我认为问题是 JavaScript 无法解析该方法path(),此方法仅在服务器端对 twig 有用。

您可以使用

方法path(),始终在{{ }}内的树枝模板中(尽管您在脚本中)。它将是这样的:

<a href="{{ path('usuario_logout') }}">Cerrar sesión</a>

这段代码是我的一个项目的一部分,它正在工作。