jQuery 1.4.1에서 JSON stringify가 누락되었습니까?
jQuery는 특정 개체 또는 문자열을 JSON 개체로 디코딩할 수 있는 기능을 가지고 있는 것 같습니다.단, 서버에 POST해야 하는 JS 오브젝트가 있어 JSON.stringify() 함수를 랩하는 유틸리티를 jQuery에서 찾을 수 없습니다.이 기능은 Chrome, Safari 4, FF3.6 및 IE8에서 볼 수 있지만 이전 브라우저에서는 볼 수 없습니다.이를 지원하는 브라우저에서 네이티브로 사용할 수 있지만 그렇지 않으면 Crockford의 JSON 스크립트를 사용해야 합니다.
JSON 인코딩 및 디코딩을 처리하는 jQuery에 Crockford 스크립트를 대체하는 빌트인이 있습니까?
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는 네이티브로 JSON 문자열을 디코딩할 수 있습니다.
다만, 인코딩의 경우는, jquery-json 플러그 인 밖에 모릅니다.
jQuery는 내부적으로 이 기능을 필요로 하지 않으므로 편리한 방법을 제공하지 않습니다.
JSON.stringify()는 개체를 해당 개체의 JSON 문자열 표현으로 인코딩하는 표준적이고 권장되는 방법입니다.이는 많은 브라우저에서 네이티브 JSON 객체의 메서드로, 폴백을 제공하기 위해 json2.http://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() 함수는 필요하지 않습니다.javascript 데이터를 서버에 전송하기 위해 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
'programing' 카테고리의 다른 글
ODATA에서 json 형식을 반환하는 방법 (0) | 2023.03.26 |
---|---|
데이터 객체 배열을 json으로 변환 - Android (0) | 2023.03.26 |
json을 사용하여 JSON을 디코딩하고 있습니다.언마샬 vs json.NewDecoder.디코드 (0) | 2023.03.26 |
올바른 형식으로 JSON 파일에 쓰는 방법 (0) | 2023.03.26 |
원인: org.hibernate.휴지 상태예외:Language Resolution 접근'hibernate.dialect'가 설정되지 않은 경우 정보는 null일 수 없습니다. (0) | 2023.03.26 |