Symfony:如何在 AJAX 调用中重定向到新页面?
我让 jquery 发送一个 AJAX 请求,该请求执行一些检查,然后应该重定向到另一个页面或返回数据。一切工作正常,除了我无法在我的操作文件中强制重定向。我已经尝试过:
$this->redirect('@new_page'); // DOESN'T WORK
并且...
$this->context->getController()->redirect('@new_page'); // DOESN'T WORK
我认为有一种方法可以将重定向 URL 返回到 Jquery 并从那里进行重定向,但我更愿意在我的操作中处理重定向。
这可能吗?
谢谢
更新:
上面的最终工作解决方案是将 TRUE/FALSE 返回到 Ajax 请求,并将以下内容添加到我的 Jquery 函数中:
if(data == true) window.location.href = "<?php echo url_for('@new_page') ?>";
else // do other stuff
新页面 URL 不需要是动态的,并且能够在首页加载时插入。在这种情况下,TRUE/FALSE 足以为 else 子句返回数据。
I've got jquery sending an AJAX request that executes some checks and then should EITHER redirect to another page or return data. Everything works fine except I'm unable to force the redirect in my actions file. I've tried:
$this->redirect('@new_page'); // DOESN'T WORK
And...
$this->context->getController()->redirect('@new_page'); // DOESN'T WORK
I think there's a way to return the redirect URL back to Jquery and redirect from there but I'd prefer to handle the redirect in my action.
Is this possible?
Thanks
UPDATE:
The final working solution the above was to return TRUE/FALSE back to the Ajax request and add the following to my Jquery function:
if(data == true) window.location.href = "<?php echo url_for('@new_page') ?>";
else // do other stuff
The new page URL didn't need to be dynamic and was able to be inserted on first page load. In this case, TRUE/FALSE sufficed for the data to be returned for the else clause.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
请记住,通过 AJAX 操作,结果(通常)会返回到回调处理程序或页面中的
DIV
元素。因此,您尝试使用的重定向仅引用此 AJAX 操作的响应,而不是整个 HTTP 页面请求。重定向可能在 symfony 中工作正常,只是它返回的响应被馈送到您的 DIV 或回调处理程序,并且它不知道如何处理 HTML。您确实需要从 AJAX 回调处理程序中触发重定向或刷新。您可能需要考虑避免完全重定向,而使用
error
回调并显示另一个包含错误消息内容的DIV
,但此error
回调如果您愿意,也可以用于重定向。Remember, with an AJAX action the result is returned (generally) to a callback handler or a
DIV
element in the page. Thus, the redirect you are trying to use only refers to this AJAX action's response, not the entire HTTP page request. The redirect is probably working fine from within symfony, just that the response it returns is being fed to yourDIV
or callback handler, and it doesn't know what to do with the HTML. You will indeed need to fire the redirect or refresh from within the AJAX callback handler.You may want to consider eschewing a full redirect in favour of using the
error
callback and displaying anotherDIV
with error message content, but thiserror
callback could be used for the redirect too, if you prefer.我已经通过下面的代码处理了这个问题,同时保留在控制器中
I have handle this one by below code,while remaining in controller