在url参数javascript中存储键值对列表。 [英] Storing a list of key value pairs in a url parameter, javascript.

查看:77
本文介绍了在url参数javascript中存储键值对列表。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设以 www.mydomain.com?param1=example 为例。

最好的方法是什么存储第二个参数,它是一个键值对列表?在那一刻我使用& param2 = key | value,key | value 。我使用垂直线将键与值分开,并使用逗号配对,等于之后的所有内容都使用 encodeURIComponent()进行编码。这很好用。

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 comma, everything after the equals is encoded using encodeURIComponent(). This works fine.

但是,用户可以控制价值......而作为明智的人类,我们都知道用户可能做的第一件事就是坚持垂直条或逗号作为破坏我的参数解析器的值之一。有一个更好的方法吗?我见过PHP用户正在讨论在URL中存储相关数组,但我正在寻找纯javascript解决方案

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 comma 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.

推荐答案

PHP(和其他服务器端语言)支持在查询字符串中传递数组。

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

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

PHP将解析GET字符串:

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 become a numeric array:

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

将被解析为:

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

更新:您还可以在JavaScript中解析查询字符串。

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

这是我制作的一个简单的jQuery插件:

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;
};

然后你可以这样做: $。parseQuery('param1 = example& param2 [] = value1& param2 [] = value2');

这篇关于在url参数javascript中存储键值对列表。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆