用在JavaScript的RequestHelper 碰到一個小小的需求,就是要根據傳入的錨(也就是url中#後面的東西啦)來顯示不同的內容,記得以前寫了的,不知道被我丟到哪去了,又要重新寫一個,順便把功能整理加強了一些,加入了取QueryString和Cookie的東西,老習慣,貼代碼.
RequestHelper.js
//功能 : 在javascript中提供QueryString/Cookie/Anchor的訪問.
/*使用 :
var Request = new RequestHelper();
var s = Request.QueryString["id"]; //取得url中的id參數.
var c = Request.Cookies["name"]; //取得id為name的cookie值.
var a = Request.Anchor; //取得url中定位的錨點名稱.
*/
//更新 : 2008-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();
}
經初步測試,沒發現問題,但不保證沒有任何bug,有用得上的,請隨便複製粘貼,有更好的方法的,請各位多多指點,我只是小菜一個,大家就磚下留情了.
另,因cookie的名稱不支援某些特殊符號,所以這裡只取了數字和字母,大家注意了,如果有其它的辦法,麻煩指點指點。呵呵!
[轉]http://www.cnblogs.com/robot/archive/2008/05/31/1211225.html