在一个web项目中,url跳转是最常用的技术之一。页面跳转可能是由于用户单击链接、按钮等引发的,也可能是系统自动产生的。根据我个人的开发经历, 在此处总结出常用的实现页面自动跳转的方法,集合了html、javascript和php的各种方法。
方法解说:1、 PHP的header实现页面跳转:header()函数的主要功能是将HTTP协议标头(header)输出到浏览器。
header()函数的定义如下:
void header (string string [,bool replace [,int http_response_code]])
案例代码://①重定向浏览器header("Location: http://www.nosee123.com");//②使用refresh可以指定如30秒后再进行页面跳转header("refresh:30;url=www.nosee123.com");//返回上一页的方法header(location:.getenv("HTTP_REFERER")); // 返回其调用页面注意:
① location和“:”号间不能有空格,否则不会跳转。
② 在用header前不能有任何的输出。哪怕是一个空格,那么在页顶会显示错误信息。
③ header后的PHP代码还会被执行
④ 要是想在重定向之后,后续的代码不会被执行,最好后面加上一个exit()函数。
2、使用javascript实现页面跳转// ①以下方式直接跳转,比较常用的方法,后面直接跟指定要跳转的地址即可。window.location.href='www.nosee123.com'//后面的href可以省略掉(如果把href改为replace则表示跳转后没有后退功能 )//更深入了解的话,这里的window还可以换成使用self、this、parent、top,分别代表不同的对象。就比如:self指代当前窗口对象;这里将不作一一解说,感兴趣的同学可以深入学习,当然也欢迎来和我讨论。//② 以下方式定时跳转setTimeout("javascript:location.href='nosee123.com'", 5000);//③使用 open 语句实现,而且可以指定是在原窗口、父窗口、子窗口或者新窗口打开window.open("www.nosee123.com","","_self");//④navigate对象包含有关浏览器的信息,也可以作为页面跳转,后面直接加要跳转的地方。没有应用于 navigator 对象的公开标准,不过所有浏览器都支持该对象。window.navigate("nosee123.com");扩展:使用javascript返回指定页面的方法//①参数是负几,就后退几次。window.history.back(-1);//②history.Go(-1);3、使用HTML meta refresh实现跳转这里的content属性表示几秒后执行跳转,比如:content=“5”表示5秒后执行跳转。//在html标签链接嵌套js跳转代码的方法返回上一步实用案例:1. 结合了倒数的javascript页面跳转实现(IE)5var second = totalSecond.innerText;setInterval("redirect()", 1000);function redirect(){totalSecond.innerText=--second;if(second<0) location.href='www.nosee123.com';}缺点:firefox不支持(firefox不支持span、div等的innerText属性)
2. 结合了倒数的javascript页面跳转实现(firefox)5var second = document.getElementById('totalSecond').textContent;setInterval("redirect()", 1000);function redirect(){document.getElementById('totalSecond').textContent = --second;if (second < 0) location.href = 'www.nosee123.com';}3. 解决Firefox不支持innerText的问题的整合方法5var second = document.getElementById('totalSecond').textContent;if (navigator.appName.indexOf("Explorer") > -1) {second = document.getElementById('totalSecond').innerText;} else {second = document.getElementById('totalSecond').textContent;}setInterval("redirect()", 1000);function redirect() {if (second < 0) {location.href = 'www.nosee123.com';} else {if (navigator.appName.indexOf("Explorer") > -1) {document.getElementById('totalSecond').innerText = second--;} else {document.getElementById('totalSecond').textContent = second--;}}}4. 这个方法比较少用,个人觉得比较麻烦var jumpurl = 'http://www.nosee123.com/';if (window.attachEvent) {document.write('');document.getElementById('exe').click();} else {document.write('');document.getElementById('exe').click();}5. javascript中弹出提示框跳转到其他页面
function logout(){if(confirm("你确定退出吗?")){window.location.href="logout.php";}}以上就是我们向大家介绍的web页面跳转实现方法,纯属个人经验,如有错误的地方欢迎指出。如有更好的方法也希望能够和你有进一步的交流。
阅读原文