栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > Web开发 > JavaScript

jQuery扩展方法实现Form表单与Json互相转换的实例代码

JavaScript 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

jQuery扩展方法实现Form表单与Json互相转换的实例代码

JQuery笔记

记两段代码,使用JQuery实现从表单获取json与后端交互,以及把后端返回的json映射到表单相应的字段上。

把表单转换出json对象

//把表单转换出json对象
  $.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("\[" + k + "\]$"), '');
 // 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对象赋值给form,使表单控件也显示相应的状态

//将josn对象赋值给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);
   }
 });
      }
    }
  }

补充:下面看下jQuery两种扩展方法

在jQuery中,有两种扩展方法

1.类方法($.extend())

   

2.对象方法($.fn.extend())


  
  

3.一般情况下,jQuery的扩展方法写在自执行匿名函数中(原因:在js中是以函数为作用域的,在函数中写可以避免自己定义的函数或者变量与外部冲突)

 

总结

以上所述是小编给大家介绍的jQuery扩展方法实现Form表单与Json互相转换的实例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对考高分网网站的支持!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/79367.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号