Get querystring array values in Javascript [duplicate]

别等时光非礼了梦想. 提交于 2019-12-10 02:08:18

问题


I have a form that uses the get method and contains an array:

http://www.example.com?name[]=hello&name[]=world

I'm trying to retrieve array values 'hello' and 'world' using JavaScript or jQuery.

I've had a look at similar solutions on Stack Overflow (e.g. How can I get query string values in JavaScript?) but they seem to only deal with parameters rather than arrays.

Is it possible to get array values?


回答1:


There you go: http://jsfiddle.net/mm6Bt/1/

function getURLParam(key,target){
    var values = [];
    if (!target) target = location.href;

    key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");

    var pattern = key + '=([^&#]+)';
    var o_reg = new RegExp(pattern,'ig');
    while (true){
        var matches = o_reg.exec(target);
        if (matches && matches[1]){
            values.push(matches[1]);
        } else {
            break;
        }
    }

    if (!values.length){
        return null;   
    } else {
        return values.length == 1 ? values[0] : values;
    }
}

var str = 'http://www.example.com?name[]=hello&name[]=world&var1=stam';

console.log(getURLParam('name[]',str));
console.log(getURLParam('var1',str));


来源:https://stackoverflow.com/questions/15865747/get-querystring-array-values-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!