【2017-6-5】AJAX 基本结构
AJAX - 网页数据异步加载
1、ashx - 一般处理程序
2、在不同的语言之间传递数据
xml - 可扩展的标记语言
json - 数据格式
对象格式:"{"key":"value","key":"value"}"
数组格式:"[{"key":"value"},{},{}]"
示例:
public void ProcessRequest(HttpContext context) { StringBuilder str = new StringBuilder();//创建一个StringBuilder str.Append("[");//添加方式.Append using (DataClassesDataContext con = new DataClassesDataContext()) { List<Users> ulist = con.Users.ToList(); int count = 0; foreach (Users u in ulist) { if (count > 0) str.Append(",");//判断如果大于0,就在前面加逗号,原因是格式固定,最后不能有逗号 str.Append("{\"username\":\"" + u.UserName + "\",\"password\":\"" + u.PassWord + "\",\"nickname\":\"" + u.NickName + "\",\"sex\":\"" + u.Sex + "\",\"birthday\":\"" + u.Birthday + "\",\"nation\":\"" + u.Nation + "\"}"); count++; } } str.Append("]"); context.Response.Write(str); context.Response.End(); }
3、jqeury.ajax基本结构
<script type="text/javascript"> $("#btn1").click(function () { $.ajax({ url: "../Handler2.ashx",//提交到哪个服务端 data: {},//传的数据,有的话就是{“”:“”},没有就{} type: "post",//用什么样的方式提交 dataType: "json",//返回的数据格式 success: function (msg) {//成功走这 $("#tbody1").html("");//清空 for (var i = 0; i < msg.length; i++) { var str = " <tr style=\"background-color: white;\">" str += " <td>" + msg[i].username + "</td>"; str += "<td>" + msg[i].password + "</td>"; str += " <td>" + msg[i].nickname + "</td>"; str += " <td>" + msg[i].sex + "</td>"; str += " <td>" + msg[i].birthday + "</td>"; str += " <td>" + msg[i].nation + "</td>"; str += "</tr>"; $("#tbody1").append(str);//添加 } }, error: function () {//不成功走这 alert('err'); } }); }); </script>