js获取url参数

对于这样一个URL
http://www.x2y2.com:80/fisker/post/0703/window.location.html?ver=1.0&id=6#imhere

我们可以用javascript获得其中的各个部分
1、 window.location.href
整个URl字符串(在浏览器中就是完整的地址栏)
本例返回值: http://www.x2y2.com:80/fisker/post/0703/window.location.html?ver=1.0&id=6#imhere

2,window.location.protocol
URL 的协议部分
本例返回值:http:

3,window.location.host
URL 的主机部分
本例返回值:www.x2y2.com

4、window.location.port
URL 的端口部分
如果采用默认的80端口(update:即使添加了:80),那么返回值并不是默认的80而是空字符
本例返回值:""

5、window.location.pathname
URL 的路径部分(就是文件地址)
本例返回值:/fisker/post/0703/window.location.html

6、window.location.search
查询(参数)部分
除了给动态语言赋值以外,我们同样可以给静态页面,并使用javascript来获得相信应的参数值
本例返回值:?ver=1.0&id=6

7、window.location.hash
锚点
本例返回值:#imhere <src="http://feeds.feedburner.com/~s/fisker?i=http://www.x2y2.com/fisker/post/0703/window.location.html" type="text/javascript" charset="utf-8">

采用正则表达式获取地址栏参数:
function GetQueryString(name)
        {
            var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
            var r = window.location.search.substr(1).match(reg);
            if(r!=null)return  unescape(r[2]);
            return null;
        }

// 调用方法
alert(GetQueryString("参数名1"));
alert(GetQueryString("参数名2"));
alert(GetQueryString("参数名3"));

下面举一个例子:

若地址栏URL为:abc.html?id=123&url=http://www.maidq.com

那么,但你用上面的方法去调用:alert(GetQueryString("url"));

则会弹出一个对话框:内容就是 http://www.maidq.com

如果用:alert(GetQueryString("id"));那么弹出的内容就是 123 啦;

当然如果你没有传参数的话,比如你的地址是 abc.html 后面没有参数,那强行输出调用结果有的时候会报错:

所以我们要加一个判断 ,判断我们请求的参数是否为空,首先把值赋给一个变量:

var myid=GetQueryString("id");
        if(myid !=null && myid.toString().length>1)
        {
           GetQueryString("id");
        }

这样就不会报错了!

摘自:http://www.cnblogs.com/fishtreeyu/archive/2011/02/27/1966178.html

 
posted @ 2017-06-08 08:55  安静的女汉纸  阅读(175)  评论(0编辑  收藏  举报