js获取url参数值的两种方式

来源:互联网 发布:智慧课堂软件 编辑:程序博客网 时间:2024/05/21 13:59
方法一:采用正则表达式获取地址栏参数:( 强烈推荐,既实用又方便!)    //截取url数据方法    var getParam = function (name) {        var search = document.location.search;        //alert(search);        var pattern = new RegExp("[?&]" + name + "\=([^&]+)", "g");        var matcher = pattern.exec(search);        var items = null;        if (null != matcher) {            try {                items = decodeURIComponent(decodeURIComponent(matcher[1]));            } catch (e) {                try {                    items = decodeURIComponent(matcher[1]);                } catch (e) {                    items = matcher[1];                }            }        }        return items;    };
方法二:split拆分法function GetRequest() {    var url = location.search; //获取url中"?"符后的字串    var theRequest = new Object();    if (url.indexOf("?") != -1) {        var str = url.substr(1);        strs = str.split("&");        for(var i = 0; i < strs.length; i ++) {            theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);        }    }    return theRequest;}var Request = new Object();Request = GetRequest();// var 参数1,参数2,参数3,参数N;// 参数1 = Request['参数1'];// 参数2 = Request['参数2'];// 参数3 = Request['参数3'];// 参数N = Request['参数N'];

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

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

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

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

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

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

3,window.location.host
URL 的主机部分
本例返回值:www.maidq.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

原创粉丝点击