用在JavaScript的RequestHelper
用在JavaScript的RequestHelper
碰到一個小小的需求,是要根據(jù)傳入的錨(也是url中#后面的東西啦)來顯示不同的內(nèi)容,記得以前寫了的,不知道被我丟到哪去了,又要重新寫一個,順便把功能整理加強(qiáng)了一些,加入了取QueryString和Cookie的東西,老習(xí)慣,貼代碼.
以下為引用的內(nèi)容:RequestHelper.js //功能 : 在javascript中提供QueryString/Cookie/Anchor的訪問. /*使用 : var Request = new RequestHelper(); var s = Request.QueryString["id"]; //取得url中的id參數(shù). var c = Request.Cookies["name"]; //取得id為name的cookie值. var a = Request.Anchor; //取得url中定位的錨點(diǎn)名稱. */ //更新 : 08-05-31 RequestHelper.prototype.GetParams = function() { var result = {}; var loc = document.location.toString(); if(loc.indexOf("?") > -1) { var l = loc.lastIndexOf("#") > -1 ? loc.lastIndexOf("#") : loc.length; var param_str = loc.substring(loc.indexOf("?")+1, l); var params = param_str.split("&"); for(var x = 0; x < params.length; x++) { params[x] = params[x].split("="); result[params[x][0]] = params[x][1]; } } return result; } RequestHelper.prototype.GetCookies = function() { var result = {}; var cookie = document.cookie; if(cookie.length > 0) { var reg = /(^[a-zA-z0-9]+?|; [a-zA-z0-9]+?)=/g; var c = cookie.match(reg); if(c) { var n = 0; for(var x = 0; x < c.length; x++) { n = (x < c.length - 1) ? cookie.indexOf(c[x + 1].toString()) : cookie.length; var s = cookie.substring(cookie.indexOf(c[x].toString()),n); s = s.split("="); s[0] = s[0].replace(/^; / , ""); result[s[0]] = s[1]; } } } return result; } RequestHelper.prototype.GetAnchor = function() { var Anchor; var loc = document.location.toString() if(loc.lastIndexOf("#") > -1) { Anchor = loc.substring(loc.lastIndexOf("#")+1); } return Anchor; } function RequestHelper() { this.QueryString = this.GetParams(); this.Cookies = this.GetCookies(); this.Anchor = this.GetAnchor(); }
因cookie的名稱不支持某些特殊符號,所以只取了數(shù)字和字母。