北城已荒凉 2016-05-17 06:40 采纳率: 0%
浏览 49

如何在Symfony中使用Ajax?

I have a page with a list of items and some controls that are used for searching/sorting these items. I want these controls to work dynamically, using Ajax, but I can't find a way to use it in Symfony.

In plain PHP, I had the JS file that collected the data, then sent it to a PHP file, which triggered specified method from a class. How can I do something like that in Symfony3? Only tutorial I found was for Symfony 1.x.

  • 写回答

1条回答 默认 最新

  • weixin_33691817 2016-05-17 12:28
    关注

    If you are in a form, you can do something like :

    $(document).submit(function () {
        var url = $('form').attr('action');
        var data = $('form').serialize();
    
        $.post(url, data, function (data) {
            window.location.href = data.redirect;
        })
            .fail(function () {
                $('form').replaceWith(data.form);
            });
    });
    

    You just need to send the correct url :

    $(document).on('click', 'a', function () {
            var url = window.location.href;
    
            $.get(url, function (data) {
                $('.container').replaceWith(data);
            });
    });
    

    It is also possible to use a routing generator, simply add: "friendsofsymfony/jsrouting-bundle": "dev-master" to your composer.json.

    AppKernel.php :

    new FOS\JsRoutingBundle\FOSJsRoutingBundle()
    

    Then config it in your routing.yml :

    fos_js_routing:
        resource: "@FOSJsRoutingBundle/Resources/config/routing/routing.xml"
    

    And finally use "expose" arg in your routing :

    @Route("/{table}/index", name="beta.index", options={"expose"=true})
    

    I use annotation routing

    In your JS :

    var url = Routing.generate('beta.index', { 'table': 'foo' });
    

    Hope it'll help you :)

    评论

报告相同问题?

悬赏问题

  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 路易威登官网 里边的参数逆向
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程