JQuery筆記
記兩段代碼,使用JQuery實(shí)現(xiàn)從表單獲取json與后端交互,以及把后端返回的json映射到表單相應(yīng)的字段上。
把表單轉(zhuǎn)換出json對(duì)象
//把表單轉(zhuǎn)換出json對(duì)象 $.fn.toJson = function () { var self = this, json = {}, push_counters = {}, patterns = { "validate": /^[a-zA-Z][a-zA-Z0-9_]*(?:/[(?:/d*|[a-zA-Z0-9_]+)/])*$/, "key": /[a-zA-Z0-9_]+|(?=/[/])/g, "push": /^$/, "fixed": /^/d+$/, "named": /^[a-zA-Z0-9_]+$/ }; this.build = function (base, key, value) { base[key] = value; return base; }; this.push_counter = function (key) { if (push_counters[key] === undefined) { push_counters[key] = 0; } return push_counters[key]++; }; $.each($(this).serializeArray(), function () { // skip invalid keys if (!patterns.validate.test(this.name)) { return; } var k, keys = this.name.match(patterns.key), merge = this.value, reverse_key = this.name; while ((k = keys.pop()) !== undefined) { // adjust reverse_key reverse_key = reverse_key.replace(new RegExp("http://[" + k + "http://]$"), ''); // push if (k.match(patterns.push)) { merge = self.build([], self.push_counter(reverse_key), merge); } // fixed else if (k.match(patterns.fixed)) { merge = self.build([], k, merge); } // named else if (k.match(patterns.named)) { merge = self.build({}, k, merge); } } json = $.extend(true, json, merge); }); return json; };
將josn對(duì)象賦值給form,使表單控件也顯示相應(yīng)的狀態(tài)
//將josn對(duì)象賦值給form $.fn.loadData = function (obj) { var key, value, tagName, type, arr; this.reset(); for (var x in obj) { if (obj.hasOwnProperty(x)) { key = x; value = obj[x]; this.find("[name='" + key + "'],[name='" + key + "[]']").each(function () { tagName = $(this)[0].tagName.toUpperCase(); type = $(this).attr('type'); if (tagName == 'INPUT') { if (type == 'radio') { if ($(this).val() == value) { $(this).attr('checked', true); } } else if (type == 'checkbox') { arr = value.split(','); for (var i = 0; i < arr.length; i++) { if ($(this).val() == arr[i]) { $(this).attr('checked', true); break; } } } else { $(this).val(value); } } else if (tagName == 'SELECT' || tagName == 'TEXTAREA') { $(this).val(value); } }); } } }
補(bǔ)充:下面看下jQuery兩種擴(kuò)展方法
在jQuery中,有兩種擴(kuò)展方法
1.類方法($.extend())
<script> $.extend({ print1:function(name){ //print1是自己定義的函數(shù)名字,括號(hào)中的name是參數(shù) console.log(name) } }); $.print1("坤") ; //調(diào)用時(shí)直接$.函數(shù)名(參數(shù));</script>
2.對(duì)象方法($.fn.extend())
<body> <input type="text"> <script> $.fn.extend({ getMax:function(a,b){ var result=a>b?a:b; console.log(result); } }); $("input").getMax(1,2); //調(diào)用時(shí)要$(標(biāo)簽名).函數(shù)名(); </script></body>
3.一般情況下,jQuery的擴(kuò)展方法寫(xiě)在自執(zhí)行匿名函數(shù)中(原因:在js中是以函數(shù)為作用域的,在函數(shù)中寫(xiě)可以避免自己定義的函數(shù)或者變量與外部沖突)
<script> (function(){ $.extent({ print1:function(){ console.log(123); } }) })();</script>
總結(jié)
以上所述是小編給大家介紹的jQuery擴(kuò)展方法實(shí)現(xiàn)Form表單與Json互相轉(zhuǎn)換的實(shí)例代碼,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)武林網(wǎng)網(wǎng)站的支持!
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注