【发布时间】:2011-07-06 21:15:46
【问题描述】:
我有一个 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>
有没有一种方法可以将该对象序列化为 JSON,然后以某种可以传递到 url 的查询字符串中的方式对其进行压缩/编码?
喜欢:
var destination = 'http://mywebservice?'+encode(serialize(test));
$.get(destination, function(e)) { ... }
提前致谢
【问题讨论】:
-
大多数现代浏览器都有一个可以使用的原生 JSON 对象:
JSON.stringify(myObject);(要支持几乎所有浏览器,请使用来自json.org 的 json2.js) -
请注意,IE7 没有 JSON 对象:caniuse.com/json - 所以有一段时间,您应该使用 json2.js
-
如果您可以选择,您应该考虑通过 POST 而不是 GET 传递您的有效负载。
-
如果你使用 jQuery,那么你应该将数据作为第二个参数传递给函数。 jQuery 将负责数据的正确编码。我同意使用 JSON,如果可能,您应该使用 POST。
标签: javascript jquery json cross-domain