zoukankan      html  css  js  c++  java
  • JSON对象转化

     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 });
  • 相关阅读:
    动手动脑之异常处理
    git一些概念
    jquery each函数使用
    数据库客户端
    plotly.js
    网站跳转汇总
    jquery 实现间隔运行
    学习 在线调试
    Robot限制字典的key大写的class
    Gerrit 相关
  • 原文地址:https://www.cnblogs.com/kingge/p/2875577.html
Copyright © 2011-2022 走看看