对于初学者,我正在寻找关于symfony2中的ajax的简单教程/示例?
我有这些例子:
city.php:http://pastebin.com/Qm8LS5kh
ajax_req.js:http://pastebin.com/UqJMad24
index.html:http://pastebin.com/H1err4Yh
如何将这些内容放入Symfony2应用程序?
Jea*_*ean 104
这很容易.我将通过3个步骤说明如何在Symfony2中进行AJAX调用.对于以下示例,假设使用jQuery库.
定义必须处理AJAX调用的操作的路由.例如
AcmeHomeBundle_ajax_update_mydata:
pattern: /update/data/from/ajax/call
defaults: { _controller: AcmeHomeBundle:MyAjax:updateData }
Run Code Online (Sandbox Code Playgroud)MyAjax从Homebundle 定义控制器中的操作.例如
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));
}
Run Code Online (Sandbox Code Playgroud)AJAX在Twig模板中准备您的电话,例如:
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();});
});
Run Code Online (Sandbox Code Playgroud)
您可以使用其他AJAX调用来更改示例.
| 归档时间: |
|
| 查看次数: |
56437 次 |
| 最近记录: |