1. 程式人生 > >使用js獲取QueryString的方法小結

使用js獲取QueryString的方法小結


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta content="text/html; charset=gb2312" http-equiv="Content-Type" />
<title>QueryString獲取演示程式碼 www.jb51.net</title>
<script type="text/javascript">
//獲取QueryString的陣列
function getQueryString(){
var result = location.search.match(new RegExp("[\?\&][^\?\&]+=[^\?\&]+","g"));
for(var i = 0; i < result.length; i++){
result[i] = result[i].substring(1);
}
return result;
}
//根據QueryString引數名稱獲取值
function getQueryStringByName(name){
var result = location.search.match(new RegExp("[\?\&]" + name+ "=([^\&]+)","i"));
if(result == null || result.length < 1){
return "";
}
return result[1];
}
//根據QueryString引數索引獲取值
function getQueryStringByIndex(index){
if(index == null){
return "";
}
var queryStringList = getQueryString();
if (index >= queryStringList.length){
return "";
}
var result = queryStringList[index];
var startIndex = result.indexOf("=") + 1;
result = result.substring(startIndex);
return result;
}
//綁定當控制元件高亮選中時,點選“回車鍵”時執行的操作
//control:要繫結事件的控制元件
//func:要執行的方法
function bindEnterEvent(control, func){
control.onkeypress = function(){
if (event.keyCode == 13){
func();
}
}
}
//根據輸入的QueryString名稱獲取值
function getByName(){
var name = document.getElementById("txtQueryStringName").value;
document.getElementById("txtResult").innerHTML = getQueryStringByName(name);
}
//根據輸入的QueryString的索引獲取值
function getByIndex(){
var index = document.getElementById("txtQueryStringIndex").value;
document.getElementById("txtResult").innerHTML = getQueryStringByIndex(index);
}
</script>
</head>
<body>
<div>
<span>QueryString : </span><span id="queryString"></span>
</div>
<div>
<span>QueryString's name : </span>
<input id="txtQueryStringName" name="txtQueryStringName" type="text" />
<input name="btnGetByName" type="button" value="獲取" onclick="getByName()" />
</div>
<div>
<span>QueryString's index : </span>
<input id="txtQueryStringIndex" name="txtQueryStringIndex" type="text" />
<input name="btnGetByIndex" type="button" value="獲取" onclick="getByIndex()" />
</div>
<div>
<span>結果 :</span><span id="txtResult"></span>
</div>
<!--頁面載入時執行的操作-->
<script type="text/javascript">
//顯示所有QueryString
document.getElementById("queryString").innerHTML = getQueryString();
//為txtQueryStringName繫結回車事件
bindEnterEvent(txtQueryStringName, getByName);
//為txtQueryStringIndex繫結回車事件
bindEnterEvent(txtQueryStringIndex, getByIndex);
</script>
</body>
</html>