Symfony中的Ajax和Jquery

Nad*_*ami 6 javascript php jquery symfony

我是Symfony的初学者(版本2),我有一个用普通的基本PHP实现的项目,现在我正在重做处理Symfony框架的页面,并且到达我的jquery ajax函数,当然,事情会有所不同,我曾经这样做过:

$("#div").click(function(){
  $.post("targetFile.php",{/*parameters*/,function(data){ });
});
Run Code Online (Sandbox Code Playgroud)

问:如何使它适用于Symfony?放什么而不是targetFile.php?最有可能的路线.以及在控制器和路由器方面做些什么?我在谷歌和这里看了一眼,但没有得到任何明确的答案.问候.

Dam*_*ien 5

您真的只需要通过自定义路由替换targetFile.php.

所以如果你在routing.yml中有这个:

# app/config/routing.yml
hello:
    pattern:      /ajax/target
    defaults:     { _controller: AcmeHelloBundle:Site:index }
Run Code Online (Sandbox Code Playgroud)

你可以使用这个javascript:

$("#div").click(function(){
  $.post("/ajax/target",{/*parameters*/,function(data){ });
});
Run Code Online (Sandbox Code Playgroud)

在Symfony2端,将调用AcmeHelloBundle的SiteController方法indexAction.


小智 4

如果您在routing.yml中设置:

_admin_ajax:
    resource: "@SomethingAdminBundle/Controller/AjaxController.php"
    type:     annotation
    prefix:   /admin/ajax  
Run Code Online (Sandbox Code Playgroud)

...在控制器内部,它将处理 ajax 调用:

/**
 * @Route("/ajaxhandler", name="_admin_ajax_handler")
 */
public function handlerAction() {
    
    $isAjax = $this->get('Request')->isXMLHttpRequest();
    if ($isAjax) {
        //...
        return new Response('This is ajax response');
    }
    return new Response('This is not ajax!', 400);
}
Run Code Online (Sandbox Code Playgroud)

...然后在例如 TWIG 模板中,您应该这样调用它:

$("#div").click(function(){
  $.post("{{ url('_admin_items_add') }}",{/*parameters*/,function(data){ });
});
Run Code Online (Sandbox Code Playgroud)

...您的操作的真实路线将由模板引擎生成。