用在JavaScript的RequestHelper

來源:互聯網
上載者:User
  碰到一個小小的需求,就是要根據傳入的錨(也就是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的名稱不支援某些特殊符號,所以這裡只取了數字和字母,大家注意了,如果有其它的辦法,麻煩指點指點。呵呵!

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.