加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

如何将Ajax与Symfony2集成

发布时间:2020-12-16 03:13:16 所属栏目:百科 来源:网络整理
导读:我正在看简单的教程/关于ajax在symfony2的例子,初学者? 我有这些例子: city.php:http://pastebin.com/Qm8LS5kh ajax_req.js:http://pastebin.com/UqJMad24 index.html:http://pastebin.com/H1err4Yh 如何将它们放入Symfony2应用程序? 这很容易。 我将
我正在看简单的教程/关于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库。

>定义必须处理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调用更改示例。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读