zoukankan      html  css  js  c++  java
  • Get URL parameters & values with jQuery

    原文: http://jquery-howto.blogspot.jp/2009/09/get-url-parameters-values-with-jquery.html

    In this post, I would like to share a little jQuery code snippet that makes getting URL parameters and their values more convenient.

    Recently, while working on one of my projects, I needed to read and get parameter values from URL string of the current page that was constructed and sent by PHP script. I came across this short and sweet JavaScript code snippet by Roshambo that does just that.

    // Read a page's GET URL variables and return them as an associative array.
    function getUrlVars()
    {
        var vars = [], hash;
        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
        for(var i = 0; i < hashes.length; i++)
        {
            hash = hashes[i].split('=');
            vars.push(hash[0]);
            vars[hash[0]] = hash[1];
        }
        return vars;
    }

    The function returns an array/object with your URL parameters and their values. For example, consider we have the following URL:

    http://www.example.com/?me=myValue&name2=SomeOtherValue

    Calling getUrlVars() function would return you the following array:

    {
        "me"    : "myValue",
        "name2" : "SomeOtherValue"
    }

    To get a value of first parameter you would do this:

    var first = getUrlVars()["me"];

    // To get the second parameter
    var second = getUrlVars()["name2"];

    To make the script syntax to look more jQuery like syntax I rewrote it as an extension for jQuery:

    $.extend({
      getUrlVars: function(){
        var vars = [], hash;
        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
        for(var i = 0; i < hashes.length; i++)
        {
          hash = hashes[i].split('=');
          vars.push(hash[0]);
          vars[hash[0]] = hash[1];
        }
        return vars;
      },
      getUrlVar: function(name){
        return $.getUrlVars()[name];
      }
    });

    Now, if you include the above code in your javascript file, you can get URL parameter values in the following way:

    // Get object of URL parameters
    var allVars = $.getUrlVars();

    // Getting URL var by its nam
    var byName = $.getUrlVar('name');
  • 相关阅读:
    mysql 从5.1升级到5.5.33 后 innodb 表出错 及 innodb表修复
    (未解决)在JSTL中,session 和 sessionScope 有什么区别 ??
    ubuntu 12.04安装redis2.6.16
    SOA,不看你永远不知道的事
    Failed to retrieve procctx from ht. constr
    CUSPARSE 第三章 CUSPARAE索引和数据格式
    yii框架网址解析问题
    以图搜图相关资料
    JMeter工具的使用-ForEach
    [cocos2d-x]针对不同的设备,选取不同的自适应图片
  • 原文地址:https://www.cnblogs.com/zlog/p/5387947.html
Copyright © 2011-2022 走看看