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

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

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

  2020-05-13 我要评论

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

一、把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;
             }
         }
     });

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

复制代码 代码如下:

 var DataClass = {
     create: function () {
                 return function () {
                     this.MyInit.apply(this, arguments);//创建对象的构造函数  //arguments 参数集合  系统名称 不能写错
                 }
             }
 }
 var MyDataPack = DataClass.create();
 MyDataPack.prototype = {
     //初始化
     MyInit: function (url, operation, params) {
                 this.data = new Object();   //所有数据容量
                 var bdata = new Object();
                 bdata.url = url;            //地址
                 bdata.operation = operation;//操作
                 bdata.params = params;      //参数
                 this.data.BasicData = bdata; //基本数据
             },
     //添加数据 如:addValue("obj", "111");
     addValue: function (p, obj) {
         this.data[p] = obj;
     },
     //取得 所有标记控件的值 并写入数据
     getValueSetData: function (togName) {
                 var values = Object(); //值的集合
                 $("[subtag='" + togName + "']").each(function () {
                     //如果是input 类型 控件
                     if (this.localName == "input") {
                         //如果是text 控件
                         if (this.type == "text" || this.type == "hidden") {
                             values[this.id] = this.value;
                         }
                         else if (this.type == "...") {
                         }
                         //......
                     }
                     else if (this.localName == "...") {
                     }
                     //................
                 });
                 this.data[togName] = values;//添加到数据集合
             },
     //取值 如:getValue("BasicData")
     getValue: function (p) {
                 return this.data[p];
             },
     //获取或设置url
     getUrl: function (url) {
                 if (url)
                     this.data.BasicData["url"] = url;
                 else
                     return this.data.BasicData["url"];
             }
     ,
     //取值 转成字符串的对象 数据
     getJsonData: function () {
         return $.toJSONString(this.data);
     }
 }

三、创建绑定前台数据对象 [用来读取后台传过来的值,并绑定到前台页面]

复制代码 代码如下:

var MyDataBinder = {
    //绑定数据到 控件 data:数据 tag:标签
    Bind: function (data, Tag) {
        var MJson = $.parseJSON(data);
        //只绑定 标记 了的 标签
        $("[bindtag='" + Tag + "']").each(function () {
            if (this.localName == "input") {
                if (MJson[this.id]) //如果后台传了值
                    $(this).attr("value", MJson[this.id]);
            }
            else if (this.localName == "...") {
            }
            //....
        });
    }
};

四、使用示例

前台html:

复制代码 代码如下:

 <table>
     <tr>
         <th>一</th>
         <th>二</th>
         <th>三</th>
     </tr>
     <tr>
         <td id="td1"><input type="text" id="inp_1" subtag="subtag" bindtag="bind" /></td>
         <td id="td2"><input type="text" id="inp_2" subtag="subtag" value="我只是测试一下下" /></td>
         <td><input type="text" id="inp_3" subtag="subtag" bindtag="bind" /></td>
     </tr>      
 </table>

前台js:

复制代码 代码如下:

 //====================使用示例======================================
 var MyDataPack = new MyDataPack("Handler1.ashx", "CESHI", "");
 MyDataPack.getValueSetData("subtag");//将控件数据写入对象   “subtag”为要取 控件 值 的标签
 //-------------------传前台值到后台---------------
 $.post(MyDataPack.getUrl(), MyDataPack.getJsonData(), function (data) {
     //-------------------绑定后台值到前台-----------------
     MyDataBinder.Bind(data, "bind");  //"bind" 为 要绑定控件的 标签
 });

后台:

复制代码 代码如下:

public void ProcessRequest(HttpContext context)
{
    context.Response.ContentType = "text/plain";
    //====================取前台值=============================================
    //因为后台传过来的是 json对象 转换后的字符串  所以 所有数据都 做为一个参数传过来了
    var values = context.Request.Form[0];
    //需要引入程序集System.Web.Extensions.dll
    JavaScriptSerializer _jsSerializer = new JavaScriptSerializer();
    //将 json 对象字符串  转成 Dictionary 对象
    Dictionary<string, Dictionary<string, string>> dic = _jsSerializer.Deserialize<Dictionary<string, Dictionary<string, string>>>(values);
    //现在 dic 里面就包含了 所有前台传过来的值 想怎么用 就怎么用了。
    string inp_2 = dic["subtag"]["inp_2"];//这样就直接取到了前台 页面 id为 inp_2 的 控件value 值
    //=====================传值到前台============================================
    Dictionary<string, string> dic2 = new Dictionary<string, string>();
    dic2.Add("inp_1", "修改1");//这里只用对应控件id 传值即可
    dic2.Add("inp_2", "修改2");
    dic2.Add("inp_3", "修改3");
    context.Response.Write(_jsSerializer.Serialize(dic2));
}

小伙伴们对使用json实现前后台传值是否了解清楚了呢,有问题的话,就给我留言吧

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们