구조 AJAX 매개 변 수 를 통 해 폼 요소 JSON 상호 전환 실현

ajax 서버 데 이 터 를 제출 하고 변환 방법 을 정리 합 니 다.
HTML:

<form id="fm" name="fm" action="">
<input name="UserName" type="text" value="UserName1"/>
</form>
<input name="UserId" id="UserId" type="text" value="UserId1"/> 
1.폼 요 소 를 QueryString 으로 전환

var q = $('#fm,#UserId').serialize(); //q = UserName=UserName1&UserId=UserId1 
2.문자열,JSON 상호 변환

var obj = jQuery.parseJSON('{"name":"John"}');
alert( obj.name === "John" ); 
jquery-json 플러그 인 을 이용 하여 변환 을 실현 할 수 있 으 며,예 시 를 직접 참조 할 수 있 습 니 다.

var thing = {plugin: 'jquery-json', version: 2.3};
var encoded = $.toJSON( thing );
// '{"plugin":"jquery-json","version":2.3}'
var name = $.evalJSON( encoded ).plugin;
// "jquery-json"
var version = $.evalJSON(encoded).version;
// 2.3 
3.폼,요소 전환 Name,Value 배열

var arr = $("#fm,#UserId").serializeArray();
/*[ 
{name: 'UserName', value: '"UserName"1'}, 
{name: 'UserId', value: 'UserId'}
] */ 
4.폼 요소 전 JSON

$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
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;
};
var obj = $('form').serializeObject();
/*obj: Object
UserId: "UserId1"
UserName: "UserName1"
__proto__: Object*/ 
5. JSON2FORM

$.getJSON('url_to_file', function(data) {
for (var i in data) {
$('input[name="'+i+'"]').val(data[i]);
}
}
Google 에서 더 강력 한 플러그 인 발견http://code.google.com/p/jquery-load-json/

data = {
"Name":"Emkay Entertainments",
"Address":"Nobel House, Regent Centre",
"Contact":"Phone"
} 
$('div#data').loadJSON(data);
<div id="data">
<h1 id="Name">Emkay Entertainments</h1>
<label for="Address">Address:</label>
<span id="Address">Nobel House, Regent Centre</span> 
<label for="Contact">Contact by:</label>
<span id="Contact">Phone</span>
</div> 

좋은 웹페이지 즐겨찾기