前台
<script src="js/jquery-1.8.3.min.js"></script> <script src="js/jsrender.js"></script> <!-------------jsrender--------------> <script id="tmpl" type="text/x-jsrender"> <table width="500px"> <tr> <td>用户名</td> <td>密码</td> <td>邮箱</td> <td>邮箱</td> </tr> {{for #data.p }} <tr> <td>{{:Username}}</td> <td>{{:UserPass}}</td> <td>{{:UserEmail}}</td> <td><a name="del" userid="{{:ID}}" href="javascript:void(0);">删除</a></td> </tr> {{/for}} </table> </script>
html部分
<div> 用户名: <input type="text" name="UserNmae" id="UserName" value="" /><br /> 密码: <input type="password" name="UserPass" id="UserPass" value="" /><br /> 邮箱:<input type="text" name="Email" id="UserEmail" value="" /><br /> <input type="submit" name="btn" id="btn" value="提交" /> <hr /> <!---中间数据循环--> <div id="dl"></div> </div>
<script> function deleteUser() { $('a[name="del"]').click(function () { //alert($(this).attr('userid')); $.post("deleteUser.ashx", { id: $(this).attr('userid') }, function (r) { if (r == 1) { alert('删除成功!'); LoadData(); } else { alert('删除失败!'); } }) }) } function LoadData() { //动态添加购物车信息jsrend $.ajax({ url: "GetUsers.ashx", type: "get", dataType: "json", success: function (r) { if (r.flag == 1) { var array = r.list; var html = $('#tmpl').render({ p: array }); $('#dl').html(html); deleteUser(); } }, error: function () { alert('无数据'); } })//end ajax } $(function () { //加载数据 LoadData(); //添加按钮的单击事件 $('#btn').click(function () { var username = $('#UserName').val(); var userPass = $('#UserPass').val(); var useremail = $('#UserEmail').val(); var data = { username: username, userpass: userPass, useremail: useremail }; $.post("InsertUser.ashx", data, function (r) { if (r == "添加成功!") { alert(r); $('#UserName').val(''); $('#UserPass').val(''); $('#UserEmail').val(''); LoadData(); } else { alert(r); } }) }) deleteUser(); }) </script>
后台
context.Response.ContentType = "text/plain"; string sqlstr = "select * from UserInfo"; DataTable dt = DbHelper.ExeTable(sqlstr); List<UserInfo> list = new List<UserInfo>(); if (dt.Rows.Count > 0) { foreach (DataRow dr in dt.Rows) { UserInfo user = RowToObj(dr); list.Add(user); } } JavaScriptSerializer js = new JavaScriptSerializer(); var data = new { list = list, flag = 1 }; string r = js.Serialize(data); context.Response.Write(r);