code

jQuery 1.4.1에서 JSON stringify 누락?

codestyles 2020. 10. 22. 08:04
반응형

jQuery 1.4.1에서 JSON stringify 누락?


분명히 jQuery는 주어진 객체 또는 문자열을 JSON 객체로 디코딩하는 기능을 가지고 있습니다. 그러나 서버에 다시 POST해야하는 JS 개체가 있으며 JSON.stringify () 함수를 래핑하는 jQuery에서 유틸리티를 찾을 수 없습니다. 이 기능은 Chrome, Safari 4, FF3.6 및 IE8에서 찾을 수 있지만 이전 브라우저에서는 찾을 수 없습니다. 이를 지원하는 브라우저에서 기본적으로 사용할 수 있지만 그렇지 않으면 Crockford의 JSON 스크립트를 사용하도록 강제로 돌아갑니다.

Crockford 스크립트를 대신하는 JSON 인코딩 및 디코딩을 처리하는 jQuery가 내장되어 있습니까?


http://www.json.org/js.html 을 확인해 보십시오.


"Closure Library"(Google)를 사용하여 크로스 브라우저 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는 기본적으로 jQuery.parseJSON().

인코딩의 경우 플러그인 만 알고 있습니다 .jquery-json


jQuery는 내부적으로이 기능이 필요하지 않으므로이를위한 편리한 방법을 제공하지 않습니다.

JSON.stringify ()는 객체를 해당 객체의 JSON 문자열 표현으로 인코딩하는 표준 및 권장 방법입니다. 많은 브라우저에서 네이티브 JSON 객체의 메서드이며, 폴백을 제공하려면 json2.js (https://github.com/douglascrockford/JSON-js)를 사용하는 것이 좋습니다.


stewe의 답변을 기반으로하기 위해 Advanced 가 켜진 클로저 컴파일러 는 여러 문자 변수로 전역 네임 스페이스를 오염시키는 스크립트를 제공합니다. 그래서 다음과 같이 익명의 함수 호출로 래핑합니다.

(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를 사용하는 일반적인 경우를 예로 들어 보면 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 참조 ).

그러나 이러한 형식의 직렬화는 대부분의 (전부는 아님) 애플리케이션에 적합합니다.

참고 URL : https://stackoverflow.com/questions/2277405/json-stringify-missing-from-jquery-1-4-1

반응형