使用ajax symfony2加载视图 [英] load view using ajax symfony2
问题描述
我是symfony2的新手,当用户单击div时,使用ajax加载视图时遇到了一些问题.使用Firebug,我可以看到返回了数据,但是无法将结果附加到页面中.
I'm very new to symfony2 and I'm getting some problems to load a view using ajax when the user clicks on a div. Using firebug I can see the data is returned but I can not append the result in the page.
我的代码: //默认控制器
My Code: //Default Controller
public function indexAction($num, Request $request)
{
$request = $this->getRequest();
if($request->isXmlHttpRequest()){
$content = $this->forward('PaginationBundle:Default:ajax');
$res = new Response($content);
return $res;
}
return $this->render('PaginationBundle:Default:index.html.twig', array('num' => $num));
}
public function ajaxAction()
{
return $this->render('PaginationBundle:Default:page.html.twig');
}
}
我的Js: 点击#target时,我想在div中加载page.html.twig
My Js: When clicking on #target, I'd like to load page.html.twig in my div
$("div#target").click(function(event){
t = t +1;
$.ajax({
type: "POST",
cache: "false",
dataType: "html",
success: function(){
$("div#box").append(data);
}
});
});
我在控制器中使用isXmlHttpRequest()来检测它是否是加载ajaxAction的ajax请求.我在firebug上看到了该视图,但未将其附加在div#box中. div#box存在于index.html.twig
I'm using isXmlHttpRequest() in my controller to detect if it's an ajax request to load ajaxAction. I get that view on firebug but it's not appended in my div#box. div#box exists in index.html.twig
提前感谢大家
推荐答案
在您的 $("div#target").click(function(event)事件,您没有在ajax调用中指定url参数,另一件事是,您必须在'success'内指定一个参数 Ajax调用参数.
In your $("div#target").click(function(event) event you didn't specify the url parameter in ajax call, and another thing is you must specify an argument inside the 'success' parameter of ajax call.
$("div#target").click(function(event){
t = t +1;
$.ajax({
type: "POST",
url: "{{path('yourpath-means header name in routing.yml')}}",
cache: "false",
dataType: "html",
success: function(result){
$("div#box").append(result);
}
});
});
希望这会有所帮助... 编码愉快
Hope this helps... Happy coding
这篇关于使用ajax symfony2加载视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!