只是想知道Javascript中是否有内置的东西可以接受表单并返回查询参数,例如:“var1=value&var2=value2&arr[]=foo&arr[]=bar…”
我已经想了很多年了。
只是想知道Javascript中是否有内置的东西可以接受表单并返回查询参数,例如:“var1=value&var2=value2&arr[]=foo&arr[]=bar…”
我已经想了很多年了。
当前回答
我知道这个回答有点晚了,但效果很好……
var obj = {
a:"a",
b:"b"
}
Object.entries(obj).map(([key, val])=>`${key}=${val}`).join("&");
注意:对象。条目将返回键、值对
上面一行的输出将是a=a&b=b
希望它能帮助到一些人。
快乐的编码…
其他回答
jQuery可以通过$.param来实现
$.param({ action: 'ship', order_id: 123, fees: ['f1', 'f2'], 'label': 'a demo' })
// -> "action=ship&order_id=123&fees%5B%5D=f1&fees%5B%5D=f2&label=a+demo"
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>");
谷歌需要学习这个技巧。我试图报告这个问题,但他们似乎并不在意。
不,我认为标准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。 这可以帮助你连接基本url,路径,哈希和参数。
var url = buildUrl('http://mywebsite.com', {
path: 'about',
hash: 'contact',
queryParams: {
'var1': 'value',
'var2': 'value2',
'arr[]' : 'foo'
}
});
console.log(url);
你可以通过npm https://www.npmjs.com/package/build-url下载
演示:
;(function () { 'use strict'; var root = this; var previousBuildUrl = root.buildUrl; var buildUrl = function (url, options) { var queryString = []; var key; var builtUrl; var caseChange; // 'lowerCase' parameter default = false, if (options && options.lowerCase) { caseChange = !!options.lowerCase; } else { caseChange = false; } if (url === null) { builtUrl = ''; } else if (typeof(url) === 'object') { builtUrl = ''; options = url; } else { builtUrl = url; } if(builtUrl && builtUrl[builtUrl.length - 1] === '/') { builtUrl = builtUrl.slice(0, -1); } if (options) { if (options.path) { var localVar = String(options.path).trim(); if (caseChange) { localVar = localVar.toLowerCase(); } if (localVar.indexOf('/') === 0) { builtUrl += localVar; } else { builtUrl += '/' + localVar; } } if (options.queryParams) { for (key in options.queryParams) { if (options.queryParams.hasOwnProperty(key) && options.queryParams[key] !== void 0) { var encodedParam; if (options.disableCSV && Array.isArray(options.queryParams[key]) && options.queryParams[key].length) { for(var i = 0; i < options.queryParams[key].length; i++) { encodedParam = encodeURIComponent(String(options.queryParams[key][i]).trim()); queryString.push(key + '=' + encodedParam); } } else { if (caseChange) { encodedParam = encodeURIComponent(String(options.queryParams[key]).trim().toLowerCase()); } else { encodedParam = encodeURIComponent(String(options.queryParams[key]).trim()); } queryString.push(key + '=' + encodedParam); } } } builtUrl += '?' + queryString.join('&'); } if (options.hash) { if(caseChange) builtUrl += '#' + String(options.hash).trim().toLowerCase(); else builtUrl += '#' + String(options.hash).trim(); } } return builtUrl; }; buildUrl.noConflict = function () { root.buildUrl = previousBuildUrl; return buildUrl; }; if (typeof(exports) !== 'undefined') { if (typeof(module) !== 'undefined' && module.exports) { exports = module.exports = buildUrl; } exports.buildUrl = buildUrl; } else { root.buildUrl = buildUrl; } }).call(this); var url = buildUrl('http://mywebsite.com', { path: 'about', hash: 'contact', queryParams: { 'var1': 'value', 'var2': 'value2', 'arr[]' : 'foo' } }); console.log(url);