用在JavaScript的RequestHelper [转]

用在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

原文地址:https://www.cnblogs.com/witer666/p/1211368.html