开发者

Good way to serialize a list? - Javascript/AJAX

开发者 https://www.devze.com 2023-02-01 05:03 出处:网络
just felt like asking this as there are always jewels popping up on stackoverflow :) What I have is the following list:

just felt like asking this as there are always jewels popping up on stackoverflow :)

What I have is the following list:

list1 = [['command','arg1','arg2'], ['command2','arg1'], ... ]

How would you recommend to transform it into a string in order to be passed as ONE GET argument?

e.g.

http://webgame_site.com/command_list/?data=...

What I am currently doing is separating lists using commas , ; , but I don't like this idea as the method would break if I decide to introduce these within strings.

I'm trying to be as compact as possible.


One idea I've had is to encode the list into base64:

[['command','arg1','arg2'], ['command2','arg1']]
=> "W1snY29tbWFuZCcsJ2FyZzEnLCdhcmcyJ10sWydjb21tYW5kMicsJ2FyZzEnXV0="
开发者_StackOverflow中文版

which is shorter than URIencode


Any ideas? :)


Convert it to json then encode the characters using encodeURI.

var list1 = [['command','arg1','arg2'], ['command2','arg1']];
var encoded = encodeURI(JSON.stringify(list1));

alert(encoded);

Edit for base64:

var list1 = [['command','arg1','arg2'], ['command2','arg1']];
var encoded = btoa(JSON.stringify(list1));

alert(encoded);
alert(atob(encoded));


jQuery.param() sounds good.

0

精彩评论

暂无评论...
验证码 换一张
取 消