How to convert URL parameters to a JavaScript object?

前端 未结 30 1367
时光取名叫无心
时光取名叫无心 2020-11-22 13:57

I have a string like this:

abc=foo&def=%5Basf%5D&xyz=5

How can I convert it into a JavaScript object like this?

{
          


        
30条回答
  •  [愿得一人]
    2020-11-22 14:44

    FIRST U NEED TO DEFINE WHAT'S A GET VAR:

    function getVar()
    {
        this.length = 0;
        this.keys = [];
        this.push = function(key, value)
        {
            if(key=="") key = this.length++;
            this[key] = value;
            this.keys.push(key);
            return this[key];
        }
    }
    

    Than just read:

    function urlElement()
    {
        var thisPrototype = window.location;
        for(var prototypeI in thisPrototype) this[prototypeI] = thisPrototype[prototypeI];
        this.Variables = new getVar();
        if(!this.search) return this;
        var variables = this.search.replace(/\?/g,'').split('&');
        for(var varI=0; varI

    and use like:

    var mlocation = new urlElement();
    mlocation = mlocation.Variables;
    for(var key=0;key

提交回复
热议问题