在 jQuery 中序列化为 JSON [英] Serializing to JSON in jQuery

查看:35
本文介绍了在 jQuery 中序列化为 JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要序列化一个对象以JSON.我正在使用 jQuery.有没有标准"的方法来做到这一点?

I need to serialize an object to JSON. I'm using jQuery. Is there a "standard" way to do this?

我的具体情况:我定义了一个数组,如下所示:

My specific situation: I have an array defined as shown below:

var countries = new Array();
countries[0] = 'ga';
countries[1] = 'cd';
...

我需要把它变成一个字符串传递给 $.ajax() 像这样:

and I need to turn this into a string to pass to $.ajax() like this:

$.ajax({
    type: "POST",
    url: "Concessions.aspx/GetConcessions",
    data: "{'countries':['ga','cd']}",
...

推荐答案

JSON-js -JavaScript 中的 JSON.

JSON-js - JSON in JavaScript.

要将对象转换为字符串,请使用 JSON.stringify:

To convert an object to a string, use JSON.stringify:

var json_text = JSON.stringify(your_object, null, 2);

要将 JSON 字符串转换为对象,请使用 JSON.parse:

To convert a JSON string to object, use JSON.parse:

var your_object = JSON.parse(json_text);

最近由 John Resig<​​/a> 推荐:

It was recently recommended by John Resig:

...请开始迁移您使用 JSON 的应用程序Crockford 的 json2.js.它是完全与 ECMAScript 5 兼容规范并优雅地降级如果本机(更快!)实现存在.

...PLEASE start migrating your JSON-using applications over to Crockford's json2.js. It is fully compatible with the ECMAScript 5 specification and gracefully degrades if a native (faster!) implementation exists.

事实上,我昨天刚刚在 jQuery 中进行了更改,它利用了JSON.parse 方法(如果存在),现在已完全指定.

In fact, I just landed a change in jQuery yesterday that utilizes the JSON.parse method if it exists, now that it has been completely specified.

我倾向于相信他在 JavaScript 问题上所说的话:)

I tend to trust what he says on JavaScript matters :)

所有现代浏览器(以及许多非古代浏览器)都支持 JSON 对象.Crockford 的 JSON 库的当前版本将仅定义 JSON.stringifyJSON.parse 如果它们尚未定义,则保留任何浏览器本机实现.

All modern browsers (and many older ones which aren't ancient) support the JSON object natively. The current version of Crockford's JSON library will only define JSON.stringify and JSON.parse if they're not already defined, leaving any browser native implementation intact.

这篇关于在 jQuery 中序列化为 JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆