首页 > 开发 > Javascript > 正文

JS基于Location实现访问Url、重定向及刷新页面的方法分析

2020-02-25 02:03:07
字体:
来源:转载
供稿:网友

本文实例讲述了JS基于Location实现访问Url、重定向及刷新页面的方法。分享给大家供大家参考,具体如下:

js通过Location实现访问Url,重定向,刷新页

web中经常会使用到刷新页面,访问url、重定向请求的功能。

javascript提供了许多方法访问,修改当前用户在浏览器中访问的url.所有的这些技术都是基于location对象的。它是作为window对象的属性。你可以生成一个包含当前url的新location对象:

var currentURL=window.location;

在这片文章你将看到location对象的所有属性和方法,你将学到:

怎么读取url不同部分 怎么重定向网页 怎么自动刷新或重载页面.

1.分析url

URL有6部分组成,一些是可选的:

<协议>//<域名>:<端口>/<路径><查询参数><hash>
<protocol>//<hostname>:<port>/<pathname><search><hash>

协议和域名是必须项,其它是可选项。

下面是一个包含所有部分的URL例子:

http://www.example.com:80/example.cgi?x=3&y=4#results

在这个例子中, http: 是 协议, www.example.com 是 域名, 80 是端口, /example.cgi 是路径, ?x=3&y=4是查询字符串, #results是hash, 或页面内部的锚点.

2.通过Location读取当前的URL

你可以使用location对象的protocol,hostname,port,pathname,search,hash属性访问URL各个部分。你还可以使用下面属性:

host
  包含域名和端口例如: www.example.com:80

href
  包含整个URL例如:http://www.example.com:80/example.cgi?x=3&y=4#results

示例:

var currentURL=window.location;alert(currentURL.href);//Displays'http://www.example.com:80/example.cgi?x=3&y=4#results'alert(currentURL.protocol);//Displays'http:'alert(currentURL.host);//Displays'www.example.com:80'alert(currentURL.hostname);//Displays'www.example.com'alert(currentURL.port);//Displays'80'alert(currentURL.pathname);//Displays'/example.cgi'alert(currentURL.search);//Displays'?x=3&y=4'alert(currentURL.hash);//Displays'#results'

3.使用Location操作URL

你可以使用location的href属性,把页面跳转到不同于当前页面的页面。

window.location.href="http://www.example.com/anotherpage.html" rel="external nofollow" ;

示例:

<input type="button" onclick="window.location.href='http://www.google.com/'"value="Visit www.google.com"/>

使用Location的href属性跳转页面,前一页的Url会保存在浏览器的history历史中。当用户点击浏览器的“后退”按钮可以返回前一页。如果你不想让返回前一页可使用Location.replace()代替:

window.location.replace("http://www.example.com/anotherpage.html");            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表