通過JavaScript擷取url中的參數資訊不是很困難,方法很多。之所以用這個方法,是覺得它利用了Regex,很簡練。
- function getQuery(name)
- {
- var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
- var r = window.location.search.substr(1).match(reg);
- if (r != null)
- return unescape(r[2]);
- return null;
- }
例如有個需求,在一個頁面中用Javascript實現根據url參數ErrType的不同的值在頁面中顯示不同的錯誤資訊:
- <div id="divError" style="color:red;font-weight:bold;text-align:center;width:100%;height:300px;padding-top:30px;"></div>
- <script language="javascript">
- // define the descriptions of errors
- var errInfos = { "1" : "The submitting user should not be allowed to review his submissions",
- "2" : "Reviewers cannot review the same submission twice",
- "3" : "Only people in the “reviewers” group should be able to access the review form"
- }
- function getQuery(name)
- {
- var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
- var r = window.location.search.substr(1).match(reg);
- if (r != null)
- return unescape(r[2]);
- return null;
- }
- var errType = getQuery( "ErrType" )
- if( errType )
- document.getElementById("divError").innerText = errInfos[errType]
- </script>