1. 程式人生 > >使用JS獲取URL中參數的方法

使用JS獲取URL中參數的方法

彈出 port there href 字串 span window subst var

1、獲取整個URL字符串

要想獲取URL中的參數,首先我們就要獲取到整個URL字符串。我們以http://localhost:8080/Charge/homePage.html?costInfoId=1為例

① 獲取(或設置) URL 的協議部分:window.location.protocol

var test = window.location.protocol;  
alert(test);  
//返回彈出:http:  

② 獲取(或設置) URL 的主機部分:window.location.host

var test = window.location.host;  
alert(test);  
//返回彈出:localhost:8080 

③ 獲取(或設置) URL 關聯的端口號碼:window.location.port

var test = window.location.port;  
alert(test);  
//返回彈出:8080(如果采用默認的80端口(即使添加了:80),那麽返回值並不是默認的80而是空字符)

④ 獲取(或設置) URL 的路徑部分也就是文件地址:window.location.pathname

var test = window.location.pathname;  
alert(test);  
//返回彈出:/Charge/homePage.html 

⑤ 獲取(或設置) URL屬性中跟在問號後面的部分:window.location.search

var test = window.location.search;  
alert(test);  
//返回彈出:?costInfoId=1

⑥ 獲取(或設置) URL屬性中在井號“#”後面的分段:window.location.hash

var test = window.location.hash;  
alert(test);  
//返回彈出:空字符(因為url中沒有)  

⑦ 獲取(或設置) 整個 URL字符串:window.location.href

var test = window.location.href;  
alert(test);  
//返回彈出:http://localhost:8080/Charge/homePage.html?costInfoId=1

2、獲取URL中的參數值

獲取了URL字符串之後就是獲取URL字符串中的參數數據信息。下面是幾種獲取參數的方法:

① 同正則表達式對比獲取參數值

function getQueryString(name){  
    var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");  
    var r = window.location.search.substr(1).match(reg);  
    if (r!=null) return r[2]; return ‘‘;  
}  

② 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 id=Request["id"];   
// var 參數1,參數2,參數3,參數N;  
// 參數1 = Request[‘參數1‘];  
// 參數2 = Request[‘參數2‘];  
// 參數3 = Request[‘參數3‘];  
// 參數N = Request[‘參數N‘];  

③ 單個參數的獲取方法

function GetRequest() {  
    var url = location.search; //獲取url中"?"符後的字串  
    if (url.indexOf("?") != -1) {  //判斷是否有參數  
        var str = url.substr(1); //從第一個字符開始 因為第0個是?號 獲取所有除問號的所有符串  
        strs = str.split("=");  //用等號進行分隔 (因為知道只有一個參數 所以直接用等號進分隔 如果有多個參數 要用&號分隔 再用等號進行分隔)  
        alert(strs[1]);     //直接彈出第一個參數 (如果有多個參數 還要進行循環的)  
    }  
}  

 

使用JS獲取URL中參數的方法