jQuery에서 JSON으로 시리얼화
개체를 JSON에 직렬로 만들어야 합니다.jQuery를 사용하고 있습니다.이를 위한 "표준" 방법이 있습니까?
구체적인 상황:다음과 같이 정의된 어레이가 있습니다.
var countries = new Array();
countries[0] = 'ga';
countries[1] = 'cd';
...
이걸 스트링으로 바꿔서 이렇게 전달해야 돼요
$.ajax({
type: "POST",
url: "Concessions.aspx/GetConcessions",
data: "{'countries':['ga','cd']}",
...
JSON-js - JavaScript의 JSON.
개체를 문자열로 변환하려면JSON.stringify
:
var json_text = JSON.stringify(your_object, null, 2);
JSON 문자열을 개체로 변환하려면JSON.parse
:
var your_object = JSON.parse(json_text);
최근 John Resig가 추천한 내용:
...JSON을 사용하는 애플리케이션의 Crockford의 json2.js로의 이행을 시작하십시오.ECMAScript 5 사양과 완전히 호환되며 네이티브(빠른!) 구현이 있는 경우 성능이 저하됩니다.
사실 어제 JSON.parse 메서드가 있는 경우 JSON.parse 메서드를 사용하는 jQuery에 변경을 입수한 지 얼마 되지 않았습니다.
JavaScript에 대해 그가 말하는 것을 신뢰하는 경향이 있습니다.
모든 최신 브라우저(및 오래된 브라우저가 아님)는 기본적으로 JSON 개체를 지원합니다.Crockford의 JSON 라이브러리의 현재 버전에서는JSON.stringify
그리고.JSON.parse
아직 정의되지 않은 경우 브라우저 네이티브 구현은 그대로 유지합니다.
저는 jquery-json을 6개월 동안 사용했는데 효과가 좋습니다.사용법은 매우 간단합니다.
var myObj = {foo: "bar", "baz": "wockaflockafliz"};
$.toJSON(myObj);
// Result: {"foo":"bar","baz":"wockaflockafliz"}
jQuery는 필요 없습니다.다음 사용:
JSON.stringify(countries);
써본 적은 없지만 Mark Gibson이 쓴 jQuery 플러그인을 사용해 보세요.
여기에는 다음 두 가지 기능이 추가됩니다.$.toJSON(value)
,$.parseJSON(json_str, [safe])
.
아니요, JSON에 시리얼화하는 표준 방법은 기존 JSON 시리얼라이제이션라이브러리를 사용하는 것입니다.이 작업을 수행하지 않으려면 자체 직렬화 방법을 작성해야 합니다.
이 방법에 대한 지침이 필요한 경우 사용 가능한 라이브러리의 출처를 조사할 것을 제안합니다.
편집: 세리아제이션 메서드를 직접 작성하는 것이 나쁘다고는 할 수 없습니다.다만, 적절한 형식의 JSON을 사용하는 것이 어플리케이션에 있어서 중요한 경우, 커스텀 메서드에 의해서 장해가 발생할 가능성이 있는 것에 대해, 「1개의 의존성」의 오버헤드를 검토할 필요가 있습니다.그 위험을 감수할 수 있을지는 당신이 결정할 일이에요
이걸 어디선가 발견했어요어디인지는 기억나지 않지만...아마도 StackOverflow :)
$.fn.serializeObject = function(){
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
않은 는, 「외부 라이브러리」가 ..toSource()
네이티브 JavaScript 메서드입니다만, 완전한 크로스 브라우저는 아닙니다.
아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 네.JSON.stringify
★★★★★★★★★★★★★★★★★」JSON.parse
의 your your.Json_PostData
를 호출하기 $.ajax
:
$.ajax({
url: post_http_site,
type: "POST",
data: JSON.parse(JSON.stringify(Json_PostData)),
cache: false,
error: function (xhr, ajaxOptions, thrownError) {
alert(" write json item, Ajax error! " + xhr.status + " error =" + thrownError + " xhr.responseText = " + xhr.responseText );
},
success: function (data) {
alert("write json item, Ajax OK");
}
});
가장 좋은 방법은 JSON 개체의 polyfill을 포함하는 것입니다.
그러나 jQuery 네임스페이스 내에서 개체를 JSON 표기법(JSON의 유효한 값)으로 직렬화하는 방법을 만들어야 하는 경우 다음과 같은 작업을 수행할 수 있습니다.
실행
// This is a reference to JSON.stringify and provides a polyfill for old browsers.
// stringify serializes an object, array or primitive value and return it as JSON.
jQuery.stringify = (function ($) {
var _PRIMITIVE, _OPEN, _CLOSE;
if (window.JSON && typeof JSON.stringify === "function")
return JSON.stringify;
_PRIMITIVE = /string|number|boolean|null/;
_OPEN = {
object: "{",
array: "["
};
_CLOSE = {
object: "}",
array: "]"
};
//actions to execute in each iteration
function action(key, value) {
var type = $.type(value),
prop = "";
//key is not an array index
if (typeof key !== "number") {
prop = '"' + key + '":';
}
if (type === "string") {
prop += '"' + value + '"';
} else if (_PRIMITIVE.test(type)) {
prop += value;
} else if (type === "array" || type === "object") {
prop += toJson(value, type);
} else return;
this.push(prop);
}
//iterates over an object or array
function each(obj, callback, thisArg) {
for (var key in obj) {
if (obj instanceof Array) key = +key;
callback.call(thisArg, key, obj[key]);
}
}
//generates the json
function toJson(obj, type) {
var items = [];
each(obj, action, items);
return _OPEN[type] + items.join(",") + _CLOSE[type];
}
//exported function that generates the json
return function stringify(obj) {
if (!arguments.length) return "";
var type = $.type(obj);
if (_PRIMITIVE.test(type))
return (obj === null ? type : obj.toString());
//obj is array or object
return toJson(obj, type);
}
}(jQuery));
사용.
var myObject = {
"0": null,
"total-items": 10,
"undefined-prop": void(0),
sorted: true,
images: ["bg-menu.png", "bg-body.jpg", [1, 2]],
position: { //nested object literal
"x": 40,
"y": 300,
offset: [{ top: 23 }]
},
onChange: function() { return !0 },
pattern: /^bg-.+\.(?:png|jpe?g)$/i
};
var json = jQuery.stringify(myObject);
console.log(json);
기본적으로 2단계 프로세스로 구성됩니다.
먼저 다음과 같이 문자열화해야 합니다.
var JSON_VAR = JSON.stringify(OBJECT_NAME, null, 2);
다음에는 '아,아,아,아,아,아,아,아,아,아,아,아,아,아,아,아,아,아,아,아.string
로로 합니다.Object
:
var obj = JSON.parse(JSON_VAR);
위의 솔루션에서 고려하지 않는 한 가지 사항은 입력이 배열되어 있는데 값이 하나만 제공된 경우입니다.
예를 들어, 백엔드가 여러 명의 사람을 예상하지만, 이 경우에는 한 명의 사람만 상대하는 경우입니다.그 후 다음 작업을 수행합니다.
<input type="hidden" name="People" value="Joe" />
그리고 이전 솔루션에서는 다음과 같이 매핑됩니다.
{
"People" : "Joe"
}
하지만 이 지도는 정말로
{
"People" : [ "Joe" ]
}
이것을 수정하려면 , 입력은 다음과 같이 됩니다.
<input type="hidden" name="People[]" value="Joe" />
또, 다음의 기능을 사용합니다(다른 솔루션에 근거하고 있습니다만, 조금 확장되어 있습니다).
$.fn.serializeObject = function() {
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (this.name.substr(-2) == "[]"){
this.name = this.name.substr(0, this.name.length - 2);
o[this.name] = [];
}
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
언급URL : https://stackoverflow.com/questions/191881/serializing-to-json-in-jquery
'it-source' 카테고리의 다른 글
문자열로 PHP 클래스 인스턴스 만들기 (1) | 2022.10.21 |
---|---|
Facebook은 브라우저의 통합 개발자 도구를 어떻게 비활성화합니까? (0) | 2022.10.21 |
(pymysql.err).OperationError) (2013, '쿼리 중 MySQL 서버에 대한 연결 끊김') (0) | 2022.10.20 |
javascript에서는 nl2br()에 상당합니다. (0) | 2022.10.20 |
MariaDB/MySql의 가상(계산) 컬럼에서 UNIX_TIMESTamp 사용 (0) | 2022.10.20 |