JavaScript 数组到 URL 编码
有没有js函数可以将数组转换为urlencoded? 我完全是 JS 新手...谢谢!...
我的数组是一个关键 &值数组.... 那么,
myData=new Array('id'=>'354313','fname'=>'Henry','lname'=>'Ford');
是一样的,
myData['id']='354313';
myData['fname']='Henry';
myData['lname']='Ford';
myData.join('&'); //returns error, it doesn't work on such array...
有什么解决办法吗?
哦,对不起…… 我有一个这样的数组
var myData=new Array('id'=>'354313','fname'=>'Henry','lname'=>'Ford');
,那么我需要将数组转换为:
id=354313&fname=Henry&lname=Ford
is there any js function to convert an array to urlencoded?
i'm totally newbie n JS... thanks!...
my array is a key & value array....
so,
myData=new Array('id'=>'354313','fname'=>'Henry','lname'=>'Ford');
is the same as
myData['id']='354313';
myData['fname']='Henry';
myData['lname']='Ford';
myData.join('&'); //returns error, it doesn't work on such array...
is there any solution?
oh sory...
i have an array like this
var myData=new Array('id'=>'354313','fname'=>'Henry','lname'=>'Ford');
then i need the array converted to be:
id=354313&fname=Henry&lname=Ford
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
试试这个:
有关为什么使用
hasOwnProperty
的解释,请查看这个“我如何循环”的答案通过或枚举 JavaScript 对象?”。Try this:
For an explanation about why use
hasOwnProperty
, take a look at this answer to "How do I loop through or enumerate a JavaScript object?".如果您使用 jQuery,可以使用 $.param()。检查此处。
的示例
使用Output
也适用于对象数组(例如来自 jQuery(form).serializeArray()):
If you use jQuery, can use $.param(). Check here .
Example of using
Output is
Also works with an array of objects (like from jQuery(form).serializeArray()) :
你可以这样做:
You can do something like this:
如果你使用对象而不是数组,你可以这样做(ES6):
If you use an object instead of an array you can do this (ES6) :
迟到了,但我所做的这个解决方案可以处理递归性和嵌套数组/对象
用法:
结果:
我知道它需要encodeURIComponent方法,但可以轻松添加
编辑,改进
现在它可以处理任何深度的嵌套数组/objects,此编辑具有相同的用法
结果:
Late to the party, but this solution I have made can handle recursivity, and nested array/object
Usage:
Result:
I know that it needs encodeURIComponent method, but can be added easily
EDIT, IMPROVEMENTS
Now it can handle any deep, with nested array/objects, this edit has the same usage
Result:
recursiveEncoded 和 recursiveDecoded 的值警报如下:
a%5Bone%5D=1&a%5Btwo%5D=2&a%5B Three%5D=3&b%5B%5D=1&b%5B%5D=2& ;b%5B%5D=3
a[一]=1&a[二]=2&a[三]=3&b[]=1&b[]=2&b[]=3
https://api.jquery.com/jQuery.param/
The values of recursiveEncoded and recursiveDecoded are alerted as follows:
a%5Bone%5D=1&a%5Btwo%5D=2&a%5Bthree%5D=3&b%5B%5D=1&b%5B%5D=2&b%5B%5D=3
a[one]=1&a[two]=2&a[three]=3&b[]=1&b[]=2&b[]=3
https://api.jquery.com/jQuery.param/
取自 jgrunds 答案,如果你想扩展数组功能
或者如果你想要一个独立的函数
Taken from jgrunds answer, if you want to extend the array functionality
Or if you want a standalone function
查看函数 escape 和 unescape。
Look at the function escape and unescape.