[英]PHP- Ajax and Redirect
i have a jquery Ajax request happening on a page.我在页面上发生了一个 jquery Ajax 请求。 On php side i am checking if the session is active and doing something.
在 php 端,我正在检查会话是否处于活动状态并执行某些操作。 If the session is not active i want to redirect the user to another page in php(header redirect).
如果会话未激活,我想将用户重定向到 php 中的另一个页面(标题重定向)。 how do i do it.
我该怎么做。
I know how to achieve it in javascript(ie if session_fail then change window.location but is there something that i can do in php/cakephp我知道如何在 javascript 中实现它(即如果 session_fail 然后更改 window.location 但我可以在 php/cakephp 中做些什么
Redirects only say "The data you requested can be found here".重定向只说“可以在此处找到您请求的数据”。
HTTP provides no way to say "Even though you requested a resource to go inside a page, you should should leave that page and go somewhere else". HTTP 无法说明“即使您请求资源进入页面,您也应该离开该页面并转到其他地方”。
You need to return a response that your JavaScript understands to mean "Go to a different location" and process it in your own code.您需要返回一个您的 JavaScript 理解为“转到不同位置”的响应,并在您自己的代码中处理它。
If I understand what you want to happen then this is how I'm implementing it.如果我了解您想要发生的事情,那么这就是我实施它的方式。 It's in Prototype instead of jQuery but it shouldn't take you long to translate:
它在 Prototype 中而不是 jQuery 中,但它不应该花很长时间来翻译:
new Ajax.Request('process.php', {
on401: function(response) {
var redirect = response.getHeader('Location');
document.location = redirect;
}
});
In your PHP, output the following if the session is inactive:在您的 PHP 中,如果会话处于非活动状态,则输出以下内容:
header('Location: http://example.com/login.php', true, 401);
exit;
This is what you would want in your php IF THIS WERE A REGULAR REQUEST, NOT AN AJAX如果这是常规请求,而不是 AJAX,这就是您在 php 中想要的
if (isset($_SESSION)) doSomething();
else header("Location: otherUrl");
Since this is an Ajax call, you are not passing control to the php, but just trying to get a response that (likely) fills a particular section of your page.由于这是一个 Ajax 调用,因此您不会将控制权传递给 php,而只是尝试获得(可能)填充页面特定部分的响应。 You do not mention what jQuery ajax function you use, but it matters.
您没有提到您使用的 jQuery ajax 函数,但这很重要。 I would imagine you are using either $.get() or $(element).load() ??
我想你正在使用 $.get() 或 $(element).load() ??
Without knowing the particulars, this is my best suggestion for you.在不知道细节的情况下,这是我给你的最好的建议。
Ajax call: $.get(url, callbackFunc);
Ajax 调用:
$.get(url, callbackFunc);
php: php:
if(isset($_SESSION)) echoSomething() else echo("redirect");
callbackFunc:回调函数:
function(data)
{ if (data == "redirect") window.location = otherUrl;
else
$("#desiredElement").html(data);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.