我的 Controller
中有一个handleAjaxAction
。在此操作中,我想根据 route
或 url
执行不同的操作。因此,我尝试使用以下方法获取当前页面的路线:
$request->attributes->get('_route');
但是,它给了我 ajax
路由 demo_ajax_update
,而不是当前页面的路由 demo_homepage
。
如何在 Ajax
操作中获取当前路线?
编辑:
我的Ajax
代码如下:
var route; <-------- Should be set as the route of the current page
$.ajax({
type: "POST",
url: Routing.generate('demo_ajax_update'),
data: JSON.stringify({id: patientId, startDate: startDate, endDate: endDate, route: route}),
dataType: "json",
success: function (data) {
// Doing something
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('Error : ' + errorThrown);
}
});
在 Controller
中:
public function handleAjaxUpdateAction(Request $request)
{
$data = json_decode($request->getContent());
if($data->route == 'demo_homepage'){
// Do something
}
elseif($data->route == 'demo_anotherroute'){
// Do something
}
}
最佳答案
在这种情况下,不使用 FOSJsRoutingBundle
的可能解决方法是将 uri 作为参数传递,并使用 match
router
的方法来获取实际的当前路由:
$this->get('router')->match($uri)
给你这个ajax调用:
var uri = window.location.pathname; // current page uri (something like `/hello/test`)
$.ajax({
type: "POST",
url: '/path/to/demo/ajax/update',
data: JSON.stringify({
id: patientId,
startDate: startDate,
endDate: endDate,
uri: uri // here you add the current uri
}),
dataType: "json",
success: function (data) {
// Doing something
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('Error : ' + errorThrown);
}
});
你的行动:
public function handleAjaxUpdateAction(Request $request)
{
$data = json_decode($request->getContent());
$possibleRoutes = $this->get('router')->match($data->uri);
if (in_array('demo_homepage', $possibleRoutes)) {
// Do something
} elseif (in_array('demo_anotherroute', $possibleRoutes)){
// Do something
}
}
但我认为我肯定会执行多个类似 AjaxUpdate 的操作。 Controller 至少有一个。这样您就不必想知道电话是从哪里来的,而且您的操作也会更短。如果您计划制作仅限 ajax 的 Controller :
HomepageAjaxController
--> updateAction
--> deleteAction
--> createAction
--> readAction
AnotherAjaxController
--> updateAction
--> deleteAction
--> createAction
--> readAction
关于ajax - Symfony2 : How to get a current route in Ajax controller?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21991918/