只是想知道Javascript中是否有内置的东西可以接受表单并返回查询参数,例如:“var1=value&var2=value2&arr[]=foo&arr[]=bar…”

我已经想了很多年了。


当前回答

如果你正在使用jQuery,你可能想要查看jQuery.param() http://api.jquery.com/jQuery.param/

例子:

var params = {
    parameter1: 'value1',
    parameter2: 'value2',
    parameter3: 'value3' 
};
var query = $.param(params);
console.log(query);

这将打印出:

parameter1=value1&parameter2=value2&parameter3=value3

其他回答

对于那些喜欢jQuery的人来说,你可以使用表单插件:http://plugins.jquery.com/project/form,它包含一个formSerialize方法。

现在回答你的问题可能太迟了。 我有同样的问题,我不喜欢不断追加字符串创建URL。所以,我开始使用$。Param techhouse解释道。 我还找到了一个URI.js库,可以轻松地为您创建url。这里有几个例子可以帮助你: 这是其中之一:

var uri = new URI("?hello=world");
uri.setSearch("hello", "mars"); // returns the URI instance for chaining
// uri == "?hello=mars"

uri.setSearch({ foo: "bar", goodbye : ["world", "mars"] });
// uri == "?hello=mars&foo=bar&goodbye=world&goodbye=mars"

uri.setSearch("goodbye", "sun");
// uri == "?hello=mars&foo=bar&goodbye=sun"

// CAUTION: beware of arrays, the following are not quite the same
// If you're dealing with PHP, you probably want the latter…
uri.setSearch("foo", ["bar", "baz"]);
uri.setSearch("foo[]", ["bar", "baz"]);`

2k20更新:使用Josh的URLSearchParams.toString()解决方案。

旧的回答:


没有jQuery

var params = {
    parameter1: 'value_1',
    parameter2: 'value 2',
    parameter3: 'value&3' 
};

var esc = encodeURIComponent;
var query = Object.keys(params)
    .map(k => esc(k) + '=' + esc(params[k]))
    .join('&');

对于不支持需要ES5的箭头函数语法的浏览器,请更改.map…行

    .map(function(k) {return esc(k) + '=' + esc(params[k]);})

我自己也不完全确定,我记得jQuery在一定程度上做到了这一点,但它根本不能处理分层记录,更不用说以php友好的方式了。

有一件事我很确定,当构建url并将产品粘贴到dom中时,不要仅仅使用字符串胶水来做,否则您将打开自己的方便之门。

For instance, certain advertising software in-lines the version string from whatever runs your flash. This is fine when its adobes generic simple string, but however, that's very naive, and blows up in an embarrasing mess for people whom have installed Gnash, as gnash'es version string happens to contain a full blown GPL copyright licences, complete with URLs and <a href> tags. Using this in your string-glue advertiser generator, results in the page blowing open and having imbalanced HTML turning up in the dom.

这个故事的寓意是:

   var foo = document.createElement("elementnamehere"); 
   foo.attribute = allUserSpecifiedDataConsideredDangerousHere; 
   somenode.appendChild(foo); 

不是:

   document.write("<elementnamehere attribute=\"" 
        + ilovebrokenwebsites 
        + "\">" 
        + stringdata 
        + "</elementnamehere>");

谷歌需要学习这个技巧。我试图报告这个问题,但他们似乎并不在意。

现在你可以用FormData和URLSearchParams做到这一点,而不需要循环任何东西。

const formData = new FormData(form);
const searchParams = new URLSearchParams(formData);
const queryString = searchParams.toString();

不过,旧的浏览器将需要一个填充。