1 (function ($) { 2 $.fn.getData = function (itemTag) { 3 var obj; 4 if (itemTag) { 5 obj = []; 6 this.find(itemTag).each(function () { 7 obj.push($(this).getData()); 8 }); 9 return obj; 10 } 11 else { 12 obj = {}; 13 this.find("input,select").each(function (i, v) { 14 if (this.name) { 15 obj[encodeURIComponent(this.name)] = encodeURIComponent($.trim($(this).val())); 16 } 17 }); 18 return obj; 19 } 20 }; 21 $.fn.setData = function (obj) { 22 if ($.isPlainObject(obj)) { 23 for (var p in obj) { 24 var element = $('input[name="' + decodeURIComponent(p) + '"]' + ',select[name="' + decodeURIComponent(p) + '"]'); 25 if (element.length > 0 && !$.isArray(obj[p])) { 26 element.val(decodeURIComponent(obj[p])); 27 } 28 } 29 } 30 }; 31 })(jQuery); 32 $.extend({ 33 toJSON: function (obj) { 34 if ($.isPlainObject(obj)) { 35 var props = []; 36 for (var p in obj) { 37 var prop = obj[p]; 38 var propStr = ''; 39 if ($.isArray(prop)) { 40 propStr += '['; 41 var items = []; 42 $.each(prop, function (i, v) { 43 if ($.type(v) == "number" || $.type(v) == "string") { 44 items.push('"' + v + '"'); 45 } 46 else { 47 items.push($.toJSON(v)); 48 } 49 }); 50 propStr += items.join(',') + ']'; 51 } 52 else { 53 propStr += '"' + prop + '"'; 54 } 55 props.push('"' + p + '":' + propStr); 56 } 57 } 58 return '{' + props.join(',') + '}'; 59 } 60 });