我需要通过查询字符串传输javascript对象

joh*_*ohn 3 javascript jquery json cross-domain

我有一个javascript对象,我需要能够通过查询字符串传递给Web服务.

比如说:

<script type="text/javascript">
var test = new Object();
test.date = new Date();
test.str = "hello world!";
test.list = new Array();
test.list.push('a');
test.list.push('b');
test.list.push('c');
</script>
Run Code Online (Sandbox Code Playgroud)

有没有一种方法可以将该对象序列化为JSON,然后以某种方式压缩/编码,可以传递给url的查询字符串?

喜欢:

var destination = 'http://mywebservice?'+encode(serialize(test));
$.get(destination, function(e)) { ... }
Run Code Online (Sandbox Code Playgroud)

提前致谢

Jen*_*and 9

你想要Douglas Crockford的json2.js:https://github.com/douglascrockford/JSON-js

var test = new Object();
test.date = new Date();
test.str = "hello world!";

var dest = 'http://mywebservice?'+encodeURIComponent( JSON.stringify(test) );
Run Code Online (Sandbox Code Playgroud)

(哦,不要使用escape(),不推荐使用.总是使用encodeURIComponent()代替)

但为什么不使用(会话)cookie呢?使用URI传递数据可能是SEO,书签,链接等的主要问题.


Mar*_*acz 5

您应该记住,查询字符串的最大长度(Wiki表示为2083个字符),因此必须小心放置太大的对象。