gpt4 book ai didi

jquery - 通过 AJAX 请求调用方法/路由时,重定向不起作用

转载 作者:行者123 更新时间:2023-12-01 03:39:41 25 4
gpt4 key购买 nike

我在 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);
}
});

当有人点击删除按钮时会触发该代码(无关紧要)。这是在 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')); 从来没有发生过,为什么呢?我该如何解决这个问题?

最佳答案

什么$this->redirect所做的基本上是返回 302 的响应http状态,即重定向。这不会被 ajax 调用解析(它等待 200 OK 状态),所以你不能这样做。

您想要实现的其他解决方案是返回常规(在我的示例中为 json )响应,其中包含您想要执行重定向的网址,并在 success 中执行此操作通过设置window.location.href回调:

JS:

$.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;
}
});

您的 Controller :

use Symfony\Component\HttpFoundation\JsonResponse;
public function removeAction(Request $request, $id = null)
{
(...)

$this->get('session')->getFlashBag()->add('message', $flashMessage);
return new JsonResponse($this->generateUrl('device_list'));
}

关于jquery - 通过 AJAX 请求调用方法/路由时,重定向不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24639788/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com