北城已荒凉 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 我想在一个软件里添加一个优惠弹窗,应该怎么写代码
  • ¥15 fluent的在模拟压强时使用希望得到一些建议
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流