通過構造AJAX參數實現表單元素JSON相互轉換_AJAX相關

來源:互聯網
上載者:User

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: ObjectUserId: "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> 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.