我正在看简单的教程/关于ajax在symfony2的例子,初学者?
我有这些例子:
> city.PHP:http://pastebin.com/Qm8LS5kh
> ajax_req.js:http://pastebin.com/UqJMad24
> index.html:http://pastebin.com/H1err4Yh
如何将它们放入Symfony2应用程序?
这很容易。
我将演示如何通过3步骤在Symfony2中进行AJAX调用。对于以下示例,假设使用jQuery库。
我将演示如何通过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调用更改示例。