weixin_33714884 2015-12-01 18:37 采纳率: 0%
浏览 67

Symfony-Ajax和Twig

I am working on Symfony2 project. And now want to add some dynamic actions. I want to use jQuery and Ajax calls and API.

Below I wrote my project model. my model

Issue is there where I put "?" on the picture.

For example I have comments in my page and 2 buttons "oldest" "newest".

Basically on the page load TWIG load comment to my view and everything works fine. Then I want to click on the button to change way of display comments. But want to do this without reloading a page. I click btn -> run JavaScript -> connect byt AJAX with API controller -> take back data from database ... And here I stuck

I have data in JSON but have no idea how to load them into my view instead a date loaded by Twig at the beginning.

That's a serious wall on my way to dynamic changes on web page. Thinking about:

  • Creating all the view in JavaScript and replace twig data on the view using jQuery like .html() or something - but there would be a lot of HTML code in JavaScript script, not sure that's right way

Maybe you know how to solve that issue in more elegant way?

  • 写回答

1条回答 默认 最新

  • 普通网友 2015-12-02 11:12
    关注

    It is not a Twig, but a JQuery concern. Here is an example.

    Route:

    my_symfony_route:
        path:     /get-filtered-list
        defaults: { _controller: "CompanyMyBundle:Comment:getFilteredList" }
        methods:  POST
    

    Controller

    public function getFilteredListAction(Request $request)
    {
        $param1= $request->request->get('param1');
        $param2= $request->request->get('param2');
    
        $result = array();
        //Fill $result with DB request
    
        return new JsonResponse($result);  
    }
    

    JQuery request

    $.ajax({ 
        type: 'POST', 
        url: "{{ path('my_symfony_route') }}",
        data: { param1: 'value', param2: 'value' }, 
        dataType: 'json',
        success: function (data) { 
            //Handle your JSON data to update the DOM
            $.each(data, function(index, element) {
                $('#myDivId').append($('<div>', {
                    text: element.name
                }));
            });
        }
    });
    
    评论

报告相同问题?

悬赏问题

  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示