jQuery从url获取数组值

时间:2010-07-06 17:02:39

标签: javascript jquery url arrays get

我有一个这样的网址:

http://www.somewhere.com/index.html?field[]=history&field[]=science&field[]=math

使用jQuery,我如何获取GET数组?

感谢。

2 个答案:

答案 0 :(得分:6)

[See it in action]

var str = "http://www.somewhere.com/index.html?field[]=history&field[]=science&field[]=math";

var match = str.match(/[^=&?]+\s*=\s*[^&#]*/g);
var obj = {};

for ( var i = match.length; i--; ) {
  var spl = match[i].split("=");
  var name = spl[0].replace("[]", "");
  var value = spl[1];

  obj[name] = obj[name] || [];
  obj[name].push(value);
}

alert(obj["field"].join(", "))​​

答案 1 :(得分:1)

/*
 * Returns a map of querystring parameters
 * 
 * Keys of type <fieldName>[] will automatically be added to an array
 *
 * @param String url
 * @return Object parameters
 */
function getParams(url) {
    var regex = /([^=&?]+)=([^&#]*)/g, params = {}, parts, key, value;

    while((parts = regex.exec(url)) != null) {

        key = parts[1], value = parts[2];
        var isArray = /\[\]$/.test(key);

        if(isArray) {
            params[key] = params[key] || [];
            params[key].push(value);
        }
        else {
            params[key] = value;
        }
    }

    return params;
}