Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
161 views
in Technique[技术] by (71.8m points)

javascript - 在jQuery中序列化为JSON [重复](Serializing to JSON in jQuery [duplicate])

This question already has an answer here:

(这个问题在这里已有答案:)

I need to serialize an object to JSON .

(我需要将对象序列化为 JSON 。)

I'm using jQuery .

(我正在使用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';
...

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

(我需要将其转换为字符串以传递给$.ajax()如下所示:)

$.ajax({
    type: "POST",
    url: "Concessions.aspx/GetConcessions",
    data: "{'countries':['ga','cd']}",
...
  ask by Herb Caudill translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

JSON-js - JSON in JavaScript.

(JSON-js - JavaScript中的JSON。)

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

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

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

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

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

var your_object = JSON.parse(json_text);

It was recently recommended by John Resig :

(它最近由John Resig推荐:)

...PLEASE start migrating your JSON-using applications over to Crockford's json2.js.

(...请开始将使用JSON的应用程序迁移到Crockford的json2.js。)

It is fully compatible with the ECMAScript 5 specification and gracefully degrades if a native (faster!) implementation exists.

(它与ECMAScript 5规范完全兼容,如果存在本机(更快!)实现,则会优雅地降级。)

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.

(事实上,我刚刚在jQuery中进行了一次更改,它使用了JSON.parse方法(如果存在的话),现在已经完全指定了。)

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

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

All modern browsers (and many older ones which aren't ancient) support the JSON object natively.

(所有现代浏览器 (以及许多不古老的旧浏览器 )本身都支持JSON对象 。)

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.

(Crockford的JSON库的当前版本将仅定义JSON.stringifyJSON.parse如果它们尚未定义),则保留任何浏览器本机实现。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...