[英]Redirect a user to a URL from input, store in cookie
I'm working on a project in which the user is sent to the directory name they entered in an input, like so:我正在处理一个项目,其中用户被发送到他们在输入中输入的目录名称,如下所示:
function sendanswer(e) {
if (e.keyCode === 13) {
e.preventDefault();
var answer = document.answerarea.input.value;
if (answer) {window.location.href = answer;}
}
}
document.answerarea.input.onkeypress = sendanswer;
This works fine.这工作正常。 But now I want for the user to be automatically redirected to the directory they specified every time they visit the page, BUT only if they didn't recieve a 404 error after navigating to the directory.但是现在我希望用户在每次访问页面时自动重定向到他们指定的目录,但前提是他们在导航到目录后没有收到 404 错误。 I imagine this would be accomplished by erasing the cookie when the 404 page is visited.我想这可以通过在访问 404 页面时擦除 cookie 来实现。
But how would the redirecting-to-cookie process work?但是重定向到 cookie 的过程是如何工作的呢?
When you get input from use set a cookie using this code:当您从 use 获得输入时,请使用以下代码设置 cookie:
function sendanswer(e) {
if (e.keyCode === 13) {
e.preventDefault();
var answer = document.answerarea.input.value;
if (answer) {
window.location.href = answer;
//SET COOKIE WITH NAME redirectPath
document.cookie="redirectPath="+ answer;
}
}
}
Now on your home page (the page which user gets on visiting your site) add following call on-page load:现在在您的主页(用户访问您网站的页面)上添加以下调用页面加载:
window.onload=function(){
var kuki = "redirectPath=";//NAME OF COOKIE WE SET
var cookies = document.cookie.split(';');
for(var i=0;i < cookies.length;i++) {
var c = cookies[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(kuki) == 0){
var path = c.substring(kuki.length,c.length);
//MOVE USER TO STORED PATH
document.location.href=path;
}
}
} }
A better approach will be to read cookie on server-side and redirect user to their favourite folder from there.更好的方法是在服务器端读取 cookie 并将用户从那里重定向到他们最喜欢的文件夹。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.