最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

jquery - Storing a list of key value pairs in a url parameter, javascript. - Stack Overflow

matteradmin12PV0评论

Assuming www.mydomain?param1=example as an example.

What is the best way to store a second parameter that is a list of key value pairs? At the minute I use &param2=key|value,key|value. I separate the key from the value using a vertical line, and the pairing with a ma, everything after the equals is encoded using encodeURIComponent(). This works fine.

However, the user has control of the value... And as sensible human beings we all know that the first thing the user will probably do is stick a vertical bar or a ma as one of the values breaking my parameter parser. Is there a better way to do this? I've seen PHP users talking about storing associated arrays in urls but I'm looking for a pure javascript solution.

Assuming www.mydomain.?param1=example as an example.

What is the best way to store a second parameter that is a list of key value pairs? At the minute I use &param2=key|value,key|value. I separate the key from the value using a vertical line, and the pairing with a ma, everything after the equals is encoded using encodeURIComponent(). This works fine.

However, the user has control of the value... And as sensible human beings we all know that the first thing the user will probably do is stick a vertical bar or a ma as one of the values breaking my parameter parser. Is there a better way to do this? I've seen PHP users talking about storing associated arrays in urls but I'm looking for a pure javascript solution.

Share Improve this question asked Aug 29, 2012 at 14:28 Jon WellsJon Wells 4,2599 gold badges41 silver badges69 bronze badges 1
  • 1 You know, you can use arrays as GET parameters: webmasterworld./forum88/5808.htm – Waleed Khan Commented Aug 29, 2012 at 14:30
Add a ment  | 

4 Answers 4

Reset to default 8

PHP (and other server-side languages) support passing arrays in the query string.

www.mydomain.?param1=example&param2[key1]=value1&param2[key2]=value2

PHP will parse the GET string as such:

array(2) {
  ["param1"]=>
  string(7) "example"
  ["param2"]=>
  array(2) {
    ["key1"]=>
    string(6) "value1"
    ["key2"]=>
    string(6) "value2"
  }
}

If you don't pass keys, it will be bee a numeric array:

www.mydomain.?param1=example&param2[]=value1&param2[]=value2

Will be parsed as:

array(2) {
  ["param1"]=>
  string(7) "example"
  ["param2"]=>
  array(2) {
    [0]=>
    string(6) "value1"
    [1]=>
    string(6) "value2"
  }
}

UPDATE: You can also parse the query string in JavaScript.

Here is a simple jQuery plugin I made:

$.parseQuery = function(str) {
    var ret = {};
    $.each(str.split("&"), function() {
        var data = this.split('='),
            name = decodeURIComponent(data.shift()),
            val = decodeURIComponent(data.join("=")).replace('+', ' '),
            nameVal = name.match(/(.*)\[(.*)\]/);

        if (nameVal === null) {
            ret[name] = val;
        }
        else {
            name = nameVal[1];
            nameVal = nameVal[2];
            if (!ret[name]) {
                ret[name] = nameVal ? {} : [];
            }
            if ($.isPlainObject(ret[name])) {
                ret[name][nameVal] = val;
            }
            else if($.isArray(ret[name])){
                ret[name].push(val);
            }
        }
    });
    return ret;
};

Then you can do: $.parseQuery('param1=example&param2[]=value1&param2[]=value2');.

A possible solution would be to escape the pipe and mas in the user input before posting them to your url.

That means sanitising the user input values and replacing | and , with something that doesn't break your code or just stripping them altogether.

To prevent casual tampering, you could add a checksum and base-64 encode your values then encodeURIComponent() the resulting string. (See How can you encode to Base64 using Javascript? and A JavaScript CRC32.)

Of course, this won't prevent someone who's really determined from messing with your values, but it will slow down people who just like to twiddle URLs.

When I think of serializing a list of key-value pairs, I immediately think of using a query-string.

For basics (JSON used to show deserialization):

foo=bar&foo=baz&fizz=buzz&alpha&beta=

is essentially:

{
    foo: [
        'bar',
        'baz'
    ],
    fizz: 'buzz',
    alpha: null,
    beta: ''
}

But special characters have to be escaped:

foo=bar%26baz

is essentially:

{
    foo: 'bar&baz'
}

What this means is that you can pass a query-string as a value in another query-string:

foo=bar%3Dbaz%26fizz%3Dbuzz

is essentially:

{
    foo: 'bar=baz&fizz=buzz'
}

And foo can be parsed to produce:

{
    bar: baz,
    fizz: buzz
}

That all being said, it's very easy to make mistakes while encoding/decoding, and as soon as you start double-encoding and double-decoding you're guaranteed to run into issues. If you can, use a single query string to contain all the necessary data, and don't embed a query-string within a query-string.

Post a comment

comment list (0)

  1. No comments so far