使用jQuery获取request url中的参数

jquery怎么得到request url中的参数呢?

其实很简单,就是循环遍历url,然后找到“&”这个符号:

demo1: js实现

下面是得到URL的数组
// 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;
}

1.URL如下

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


2.我们在浏览器中可以看到数组如下

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

3.得到相应的参数的值

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

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

demo2: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];
  }
});


获取相应的值的方法:

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

// Getting URL var by its nam
var byName = $.getUrlVar('name');

demo3: 修改url中的参数

function replaceParamVal(oldUrl, paramName, replaceWith) {
	var re = eval('/(' + paramName + '=)([^&]*)/gi');
	var nUrl = oldUrl.replace(re, paramName + '=' + replaceWith);
	return nUrl;
}

相关推荐