json实现前后台的相互传值详解

前后台的相互传值如果值太多,写的麻烦累人,且容易出错。这里整理出一套使用标记 标签属性的办法来传值, 后台取值和前台的绑定都有了大大的简化。

一、把json对象转成字符串

复制代码 代码如下:


$.extend({
         //将json对象转换成字符串   [貌似jquery没有自带的这种方法]
         toJSONString: function (object) {
             if (object == null)
                 return;
             var type = typeof object;
             if ('object' == type) {
                 if (Array == object.constructor) type = 'array';
                 else if (RegExp == object.constructor) type = 'regexp';
                 else type = 'object';
             }
             switch (type) {
                 case 'undefined':
                 case 'unknown':
                     return;
                     break;
                 case 'function':
                 case 'boolean':
                 case 'regexp':
                     return object.toString();
                     break;
                 case 'number':
                     return isFinite(object) ? object.toString() : 'null';
                     break;
                 case 'string':
                     return '"' + object.replace(/(\\|\")/g, "\\$1").replace(/\n|\r|\t/g, function () {
                         var a = arguments[0];
                         return (a == '\n') ? '\\n' : (a == '\r') ? '\\r' : (a == '\t') ? '\\t' : ""
                     }) + '"';
                     break;
                 case 'object':
                     if (object === null) return 'null';
                     var results = [];
                     for (var property in object) {
                         var value = $.toJSONString(object[property]);
                         if (value !== undefined) results.push($.toJSONString(property) + ':' + value);
                     }
                     return '{' + results.join(',') + '}';
                     break;
                 case 'array':
                     var results = [];
                     for (var i = 0; i < object.length; i++) {
                         var value = $.toJSONString(object[i]);
                         if (value !== undefined) results.push(value);
                     }
                     return '[' + results.join(',') + ']';
                     break;
             }
         }
     });

二、创建数据容器对象 [用来绑定要传给后台的前台控件值]

复制代码 代码如下:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wgxgpg.html