我在listDevice.html.twig
模板上有这段代码。
$.ajax({
type: "GET",
url: "http://dev/app_dev.php/device/" + window.id + "/remove",
crossDomain: false,
dataType: "html",
error: function(data) {
console.log("Error in Processing-----" + data.status);
}
});
当有人点击delete
按钮(无关紧要)时会触发代码。这是在DeleteController.php
处理删除的功能:
/**
* @Route("/device/{id}/remove", name="device_remove")
* @param integer $id
* @param Request $request
* @Method({"GET"})
* @Template()
* @Security("has_role('ROLE_ADMIN')")
* @return array
*/
public function removeAction(Request $request, $id = null)
{
$em = $this->getDoctrine()->getManager();
$can_delete = $em->getRepository('DeviceBundle:UnassignedDevices')->findBy(array('id' => $id));
if (count($can_delete) == 0) {
$driverHasDevice = $em->getRepository("DeviceBundle:DriverHasDevice")->findOneBy(array('device' => $id));
$deviceToRemove = $em->getRepository("DeviceBundle:Device")->findOneBy(array('id' => $id));
if ($driverHasDevice) {
$em->remove($driverHasDevice);
}
$em->remove($deviceToRemove);
$em->flush();
$flashMessage = $this->get('translator')->trans('delete.success', array('%element%' => 'device'));
}
else {
$flashMessage = $this->get('translator')->trans('devices.messages.driver.assigned');
}
$this->get('session')->getFlashBag()->add('message', $flashMessage);
return $this->redirect($this->generateUrl('device_list'));
}
两者都工作正常,我的意思是当我点击delete
按钮时路线匹配并且代码被执行但是重定向,这一行,$this->redirect($this->generateUrl('device_list'));
永远不会发生,为什么会这样?我怎么解决这个问题?
答案 0 :(得分:3)
$this->redirect
的作用基本上是以302
http状态返回响应,这是重定向。这不会被ajax调用解析(它等待200 OK
状态),所以你不能这样做。
您要实现的目标的其他解决方案是定期返回(我的示例中为json
)响应,其中包含您要执行重定向的网址,并通过设置{success
回调来执行此操作{1}}:
JS:
window.location.href
你的控制器:
$.ajax({
type: "GET",
url: "http://dev/app_dev.php/device/" + window.id + "/remove",
dataType: "json",
error: function(data) {
console.log("Error in Processing-----" + data.status);
},
success: function(urlFromController) {
window.location.href = urlFromController;
}
});
答案 1 :(得分:0)
您可能正在将原始html字符串返回到ajax调用。我做了一些研究。我相信你需要这样做:
header("Location:" + $this->generateUrl('device_list')); /* Redirect browser */
exit();
有关更详细的说明,请参阅this answer或this answer。
$.ajax({
type: "GET",
url: "http://dev/app_dev.php/device/" + window.id + "/remove",
crossDomain: false,
dataType: "html",
complete: function (data) { // add this option and see what "data" is
console.log(data);
},
error: function(data) {
console.log("Error in Processing-----" + data.status);
}
});