显然 jQuery 能够将给定的对象或字符串解码为 JSON 对象。但是,我有一个 JS 对象,需要将其 POST 回服务器,并且我在 jQuery 中找不到包装 JSON.stringify() 函数的实用程序。Chrome、Safari 4、FF3.6 和 IE8 中可以找到该功能,但早期浏览器中没有该功能。我可以在支持它的浏览器中本机使用它,但除此之外我被迫使用 Crockford 的 JSON 脚本。

是否有一些内置的 jQuery 可以处理 JSON 编码和解码来代替 Crockford 脚本?

有帮助吗?

解决方案

您可能要检查了这一点: http://www.json.org/js.html

其他提示

您可以使用“封库”(谷歌),使一个跨浏览器的JSON编码器/解码器。

刚去 http://closure-compiler.appspot.com/

和插入以下到文本字段中,然后按“编译”:

// ==ClosureCompiler==
// @compilation_level ADVANCED_OPTIMIZATIONS
// @output_file_name default.js
// @use_closure_library true
// ==/ClosureCompiler==

goog.require('goog.json');
if (!window['JSON']) window['JSON']={};
if (typeof window['JSON']['stringify'] !== 'function') window['JSON']['stringify']=goog.json.serialize;
if (typeof window['JSON']['parse'] !== 'function') window['JSON']['parse']=goog.json.parse;

jQuery的可本地解码与JSON字符串 jQuery.parseJSON()

虽然对于编码,我只知道一个插件的: jQuery的JSON

的jQuery不需要此功能在内部,因此不提供一个方便的方法来这样做。

JSON.stringify()是标准的,并建议进行编码的对象到对象的JSON字符串表示的方式。这是很多浏览器的原生JSON对象的方法,并建议您使用json2.js(https://github.com/douglascrockford/JSON-js)提供后备。

要建立在stewe的答案,关闭编译器的高级的开启为您提供了与污染一帮一个字母变量的全局命名空间的脚本。所以,我只是把它包装在一个匿名函数调用就像这样:

(function() { function g(a){var b=typeof a;if("object"==b)if(a){if(a instanceof Array)return"array";if(a instanceof Object)return b;var c=Object.prototype.toString.call(a);if("[object Window]"==c)return"object";if("[object Array]"==c||"number"==typeof a.length&&"undefined"!=typeof a.splice&&"undefined"!=typeof a.propertyIsEnumerable&&!a.propertyIsEnumerable("splice"))return"array";if("[object Function]"==c||"undefined"!=typeof a.call&&"undefined"!=typeof a.propertyIsEnumerable&&!a.propertyIsEnumerable("call"))return"function"}else return"null"; else if("function"==b&&"undefined"==typeof a.call)return"object";return b};function h(a){a=""+a;if(/^\s*$/.test(a)?0:/^[\],:{}\s\u2028\u2029]*$/.test(a.replace(/\\["\\\/bfnrtu]/g,"@").replace(/"[^"\\\n\r\u2028\u2029\x00-\x08\x10-\x1f\x80-\x9f]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:[\s\u2028\u2029]*\[)+/g,"")))try{return eval("("+a+")")}catch(b){}throw Error("Invalid JSON string: "+a);}function i(a,b){var c=[];j(new k(b),a,c);return c.join("")}function k(a){this.a=a} function j(a,b,c){switch(typeof b){case "string":l(b,c);break;case "number":c.push(isFinite(b)&&!isNaN(b)?b:"null");break;case "boolean":c.push(b);break;case "undefined":c.push("null");break;case "object":if(null==b){c.push("null");break}if("array"==g(b)){var f=b.length;c.push("[");for(var d="",e=0;e<f;e++)c.push(d),d=b[e],j(a,a.a?a.a.call(b,""+e,d):d,c),d=",";c.push("]");break}c.push("{");f="";for(e in b)Object.prototype.hasOwnProperty.call(b,e)&&(d=b[e],"function"!=typeof d&&(c.push(f),l(e,c),c.push(":"), j(a,a.a?a.a.call(b,e,d):d,c),f=","));c.push("}");break;case "function":break;default:throw Error("Unknown type: "+typeof b);}}var m={'"':'\\"',"\\":"\\\\","/":"\\/","\u0008":"\\b","\u000c":"\\f","\n":"\\n","\r":"\\r","\t":"\\t","\x0B":"\\u000b"},n=/\uffff/.test("\uffff")?/[\\\"\x00-\x1f\x7f-\uffff]/g:/[\\\"\x00-\x1f\x7f-\xff]/g; function l(a,b){b.push('"',a.replace(n,function(a){if(a in m)return m[a];var b=a.charCodeAt(0),d="\\u";16>b?d+="000":256>b?d+="00":4096>b&&(d+="0");return m[a]=d+b.toString(16)}),'"')};window.JSON||(window.JSON={});"function"!==typeof window.JSON.stringify&&(window.JSON.stringify=i);"function"!==typeof window.JSON.parse&&(window.JSON.parse=h); })();

现在您可以拨打:

var JSONString = JSON.stringify({name: 'value'});

使用 jQuery 时通常不需要 JSON.stringify() 函数。以使用ajax向服务器发送javascript数据的常见情况为例,jquery有内置函数来处理这个问题:(示例来自 http://api.jquery.com/category/ajax/)

$.post("test.php", { name: "John", time: "2pm" } );
$.post("test.php", { 'choices[]': ["Jon", "Susan"] });
$.getJSON("test.js", { name: "John", time: "2pm" }, function(json) {
    alert("JSON Data: " + json.users[3].name);
});

在上面的所有示例中,发送的 javascript 数据均由 jQuery 自动序列化。

这些情况下的序列化与 JSON.Stringify() 不同,而是将数据序列化为 html 查询字符串(请参阅:http://en.wikipedia.org/wiki/Query_string#Structure).

然而,这种形式的序列化对于大多数(但不是全部)应用程序来说都很好

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top