如何将Ajax与Symfony2集成

我正在看简单的教程/关于ajax在symfony2的例子,初学者?

我有这些例子:

> city.PHPhttp://pastebin.com/Qm8LS5kh
> ajax_req.js:http://pastebin.com/UqJMad24
> index.html:http://pastebin.com/H1err4Yh

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

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

>定义必须处理AJAX调用的操作的路由。例如。

AcmeHomeBundle_ajax_update_mydata:
  pattern:  /update/data/from/ajax/call
  defaults: { _controller: AcmeHomeBundle:MyAjax:updateData }

>从Home bundle定义MyAjax控制器中的操作。例如。

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)); 
}

>在您的Twig模板中准备您的AJAX电话,例如:

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调用更改示例。

相关文章

IE6是一个非常老旧的网页浏览器,虽然现在很少人再使用它,但...
PHP中的count()函数是用来计算数组或容器中元素的个数。这个...
使用 AJAX(Asynchronous JavaScript and XML)技术可以在不...
Ajax(Asynchronous JavaScript and XML)是一种用于改进网页...
本文将介绍如何通过AJAX下载Excel文件流。通过AJAX,我们可以...
Ajax是一种用于客户端和服务器之间的异步通信技术。通过Ajax...