小编典典

如何将Ajax与Symfony2集成

ajax

我正在寻找有关symfony2中有关ajax的简单教程/示例,供初学者使用?

我有这些例子:

如何将它们放入Symfony2应用程序中?


阅读 238

收藏
2020-07-26

共1个答案

小编典典

这很容易。我将通过3个步骤说明如何在Symfony2中进行AJAX调用。对于以下示例,假设使用jQuery库。

  • 定义必须处理AJAX调用的操作的路由。例如
        AcmeHomeBundle_ajax_update_mydata:
      pattern:  /update/data/from/ajax/call
      defaults: { _controller: AcmeHomeBundle:MyAjax:updateData }
  • 在捆绑软件中的MyAjax控制器中定义操作Home。例如
        public function updateDataAction(){
      $request = $this->container->get('request');        
      $data1 = $request->query->get('data1');
      $data2 = $request->query->get('data2');
      ...
      //handle data
      ...
      //prepare the response, e.g.
      $response = array("code" => 100, "success" => true);
      //you can return result as JSON
      return new Response(json_encode($response)); 
    }      
  • AJAXTwig模板中准备呼叫,例如:
        function aButtonPressed(){
        $.post('{{path('AcmeHomeBundle_ajax_update_mydata')}}',               
                    {data1: 'mydata1', data2:'mydata2'}, 
                function(response){
                        if(response.code == 100 && response.success){//dummy check
                          //do something
                        }

        }, "json");    
    }

    $(document).ready(function() {     
      $('button').on('click', function(){aButtonPressed();});
    });

您可以使用其他AJAX调用来更改示例。

2020-07-26