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

我已经想了很多年了。


当前回答

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

其他回答

我知道这个回答有点晚了,但效果很好……

var obj = {
a:"a",
b:"b"
}

Object.entries(obj).map(([key, val])=>`${key}=${val}`).join("&");

注意:对象。条目将返回键、值对

上面一行的输出将是a=a&b=b

希望它能帮助到一些人。

快乐的编码…

如果您不想使用库,这应该涵盖大多数/所有相同的表单元素类型。

function serialize(form) {
  if (!form || !form.elements) return;

  var serial = [], i, j, first;
  var add = function (name, value) {
    serial.push(encodeURIComponent(name) + '=' + encodeURIComponent(value));
  }

  var elems = form.elements;
  for (i = 0; i < elems.length; i += 1, first = false) {
    if (elems[i].name.length > 0) { /* don't include unnamed elements */
      switch (elems[i].type) {
        case 'select-one': first = true;
        case 'select-multiple':
          for (j = 0; j < elems[i].options.length; j += 1)
            if (elems[i].options[j].selected) {
              add(elems[i].name, elems[i].options[j].value);
              if (first) break; /* stop searching for select-one */
            }
          break;
        case 'checkbox':
        case 'radio': if (!elems[i].checked) break; /* else continue */
        default: add(elems[i].name, elems[i].value); break;
      }
    }
  }

  return serial.join('&');
}

不,我认为标准JavaScript没有内置这个功能,但Prototype JS有这个功能(当然大多数其他JS框架也有,但我不知道它们),他们称之为序列化。

I can reccomend Prototype JS, it works quite okay. The only drawback I've really noticed it it's size (a few hundred kb) and scope (lots of code for ajax, dom, etc.). Thus if you only want a form serializer it's overkill, and strictly speaking if you only want it's Ajax functionality (wich is mainly what I used it for) it's overkill. Unless you're careful you may find that it does a little too much "magic" (like extending every dom element it touches with Prototype JS functions just to find elements) making it slow on extreme cases.

创建一个URL对象并将值附加到seachParameters

let stringUrl = "http://www.google.com/search";
let url = new URL(stringUrl);
let params = url.searchParams;
params.append("q", "This is seach query");

console.log(url.toString());

输出将是

http://www.google.com/search?q=This+is+seach+query

现在回答你的问题可能太迟了。 我有同样的问题,我不喜欢不断追加字符串创建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"]);`