问题描述
我正在为初学者寻找关于 symfony2 中 ajax 的简单教程/示例?
I'm looking form simple tutorial/example about ajax in symfony2, for beginner?
我有这些例子:
city.php:http://pastebin.com/Qm8LS5kh
ajax_req.js:http://pastebin.com/UqJMad24
ajax_req.js: http://pastebin.com/UqJMad24
index.html:http://pastebin.com/H1err4Yh
index.html: http://pastebin.com/H1err4Yh
如何将这些放入 Symfony2 应用程序中?
How can these be put into a Symfony2 app?
推荐答案
很简单.我将通过 3 个步骤来说明如何在 Symfony2 中进行 AJAX 调用.对于以下示例,假设使用 jQuery 库.
It is easy.I will illustrate how to do an AJAX call in Symfony2 through 3 steps. For the following example, assume to use the jQuery library.
为必须处理 AJAX 调用的操作定义路由.例如
Define the route for the action that has to handle your AJAX call. E.g.
AcmeHomeBundle_ajax_update_mydata:
pattern: /update/data/from/ajax/call
defaults: { _controller: AcmeHomeBundle:MyAjax:updateData }
在 Home
包中的 MyAjax
控制器中定义操作.例如
Define the action in the MyAjax
controller from Home
bundle. E.g.
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
调用,例如:
Prepare your AJAX
call in your Twig
template, e.g.:
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 调用来更改示例.
You can change the example by using other AJAX calls.
这篇关于如何将 Ajax 与 Symfony2 集成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!