首页 > 代码库 > ASP.NET中使用JSON方便实现前台与后台的数据交换
ASP.NET中使用JSON方便实现前台与后台的数据交换
一、前台向后台请求数据
在页面加载时,有时需要对一些表单进行初始化,此时可以利用JQuery的 get 函数向后台发起异步请求:
//初始化函数 function initSettings() { $.get("?Action=init", function (data) { if (data =http://www.mamicode.com/= "NO") {>
其中,各表单中含有一个name属性,其值为数据库对应的字段名。 后台的响应如下:if (Action == "init") { string json = "{"; DataSet ds = new DataSet(); // 此处以加载用户信息为例 ds = DataOperation.DB.Select("select * from USER_USER where USER_ID=" + USER_ID, DataOperation.DB.GetConnType()); ds.Dispose(); if (ds.Tables[0].Rows.Count > 0) { for (int i = 0; i < ds.Tables[0].Columns.Count; i++) { json +="\"" + ds.Tables[0].Columns[i].ColumnName+"\":\""+ds.Tables[0].Rows[0][i]+"\","; } json = json.Substring(0, json.Length - 1); json += "}"; try { Response.Write(json); Response.End(); } catch (Exception) { } } else { Response.Write("NO"); Response.End(); } }二、前台向后台提交数据
在表单填好后,保存时需要向后台提交数据,利用JSON 可以很方便的获取各表单数据提交并写入到数据库。前台JS 代码如下:
<pre name="code" class="javascript">$("#saveSettings").click(function () { var json = "{"; $("#userSettings input:text").each(function () { json +="\""+$(this).attr("name")+"\":\""+$(this).val()+"\","; // 获取表单值生成 JSON 格式数据 }); json = json.substring(0, json.length - 1); json += "}"; $.post("?Action=save&json=" + json, function (data) { if (data =http://www.mamicode.com/= "NO") {>后台响应代码如下:
if (Action=="save") { string sqlstr ="update USER_USER set "; string json =Request["json"]; JavaScriptSerializer serializer = new JavaScriptSerializer(); Dictionary<string, object> data = http://www.mamicode.com/(Dictionary)serializer.DeserializeObject(json);>
上面的代码中,使用了 JavaScriptSerializer 类和 Dictionary 类来解析 JSON 数据,将 JSON 数据解析成字典,方便SQL语句的生成。
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。