一、ajax简介
AJAX = Asynchronous JavaScript and XML(异步的 JavaScript 和 XML)。(异步可以理解为多线程,这一个的加载不影响其他对服务器的访问)
AJAX 是一种用于创建快速动态网页的技术。
AJAX通过在后台与服务器进行少量数据交换,AJAX 可以使网页实现异步更新。
AJAX 不是新的编程语言,而是一种使用现有标准的新方法。
AJAX 最大的优点是在不重新加载整个页面的情况下,可以与服务器交换数据并更新部分网页内容。
AJAX 不需要任何浏览器插件,但需要用户允许JavaScript在浏览器上执行。
二、AJAX创建
以User表为例,列表展示数据,当点击按钮时展示数据
1.新建一个LINQ to SQL 类(Web.dbml),将User表和Nation表拉到类中
2.新建一个纯HTML界面(HtmlPage.html)和一个一般处理程序(userajax.ashx)
(1)body内代码
<table id="tb1" style="background-color: #00ffff; text-align: center; width: 100%;"> <thead> <tr style="color: #ff6a00;"> <td>用户名</td> <td>密码</td> <td>昵称</td> <td>性别</td> <td>生日</td> <td>年龄</td> <td>民族</td> </tr> </thead> <tbody> </tbody> </table> <input type="button" value="加载" id="btn1" />//<thead>和<tbody>为了好区分
(2)js代码部分
<script>
//点击加载按钮
$("#btn1").click(function () {
//编写ajax语句,将数据提交到某个服务端去
$.ajax({
url: "ajax/userajax.ashx",//将数据要提交到哪个服务端
data: {},//将什么数据提交到服务端去,{}内基本格式为"key":"要传的数据"
type: "post",//用什么样的方式将数据提交过去
dataType: "json",//返回一个什么样的数据类型
//请求完成
success: function (data) {
$("#tb1 tbody").empty();//清空tbody
for (i in data) {
var str = "<tr style=\"background-color: #a9ff98;\">";
str += "<td>" + data[i].username + "</td>";
str += "<td>" + data[i].password + "</td>";
str += "<td>" + data[i].nickname + "</td>";
str += "<td>" + data[i].sex + "</td>";
str += "<td>" + data[i].birthday + "</td>";
str += "<td>" + data[i].age + "</td>";
str += "<td>" + data[i].nation + "</td>";
str += "</tr>";
$("#tb1 tbody").append(str);
}
},//success
//请求失败
error: function () {
alert('服务器连接失败!!!');
}
});//ajax
});//btn1.click
</script>
(3)userajax.ashx内代码
<%@ WebHandler Language="C#" Class="userajax" %> using System; using System.Web; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text;//注意引用 public class userajax : IHttpHandler { public void ProcessRequest(HttpContext context) { //有数据接收时,用context.Request["key"];将ajax传过来的数据取出来 int count = 0;//前面是否有数据 string end = "[";//创建json对象,设置默认值,基本格式为{"key":"value","":"","":""},有多条时用[]括住,每条之间用,隔开 using (WebDataContext con = new WebDataContext()) { List<User> ulist = con.User.ToList(); foreach (User u in ulist) { //前面有数据 if (count>0) { end += ","; } end += "{\"username\":\""+u.UserName+"\",\"password\": \""+u.PassWord+"\",\"nicknane\":\""+u.NickName+"\",\"sex\": \""+u.SexStr+"\",\"birthday\": \""+u.BirStr+"\",\"age\":\""+u.Age+"\",\"nation\":\""+u.NationName+"\" }"; count++; } } end += "]"; context.Response.Write(end); context.Response.End(); } public bool IsReusable { get { return false; } } }
三、json与xml
xml和json的作用:在不同语言之间进行数据传递
最早使用的数据类型是 xml
优势:
A.格式统一,符合标准;
B.容易与其他系统进行远程交互,数据共享比较方便。
劣势:
1、代码量较大
2、结构不清晰
3、解析起来麻烦
现在使用的数据类型是 json
优势:
1、结构清晰
2、类似于面向对象的解析方式
附: ajax与jQuery实现省市区三级联动:
<div>
<asp:DropDownList ID="DropDownList1" runat="server"></asp:DropDownList>
<asp:DropDownList ID="DropDownList2" runat="server"></asp:DropDownList>
<asp:DropDownList ID="DropDownList3" runat="server"></asp:DropDownList>
</div>
bind1($("#DropDownList1"), '0001', '1'); function bind1(drop, pc, key) { $.ajax({ url: "ajax/china.ashx", data: { "pcode": pc }, type: "post", dataType: "json", success: function (data) { drop.empty(); for (i in data) { var str = "<option value=\"" + data[i].code + "\">" + data[i].name + "</option>"; drop.append(str); } if (key == "1") { bind1($("#DropDownList2"), $("#DropDownList1").val(), '2'); } if (key == "2") { bind1($("#DropDownList3"), $("#DropDownList2").val(), '3'); } }, error: function () { alert('服务器连接失败!'); } }); } $("#DropDownList1").change(function () { bind1($("#DropDownList2"), $(this).val(), '2'); }); $("#DropDownList2").change(function () { bind1($("#DropDownList3"), $(this).val(), '3'); }); js代码
using System; using System.Web; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; public class china : IHttpHandler { public void ProcessRequest (HttpContext context) { string pcode = context.Request["pcode"]; StringBuilder end = new StringBuilder(); int count = 0; end.Append("["); using (mydbDataContext con = new mydbDataContext()) { List<ChinaStates> clist = con.ChinaStates.Where(r => r.ParentAreaCode == pcode).ToList(); foreach (ChinaStates c in clist) { if (count > 0) end.Append(","); end.Append("{\"code\":\""+c.AreaCode+"\",\"name\":\""+c.AreaName+"\"}"); count++; } } end.Append("]"); context.Response.Write(end); context.Response.End(); } public bool IsReusable { get { return false; } } } china.ashx
ajax完整结构
//编写ajax语句,将数据提交到某个服务端去 $.ajax({ url: "ajax/Login.ashx",//将数据要提交到哪个服务端 data: { "un": $("#txt_uname").val().trim(), "pwd": $("#txt_pwd").val() },//将什么数据提交到服务端去,{}内基本格式为"key":"要传的数据" type: "post",//用什么样的方式将数据提交过去 dataType: "json",//返回一个什么样的数据类型 success: function (data) {//请求完成 if (data.has == '1') { $("#btn1").attr("disabled", "disabled").val('跳转中...'); window.setTimeout(function () { window.location.href = "HtmlPage2.html"; }, 3000);//休眠三秒。模拟网络卡顿 } else { $("#sp1").text("用户名密码输入错误!"); $("#btn1").removeAttr("disabled").val('登录'); } }, error: function () {//服务器连接错误 $("#sp1").text("服务器连接失败!"); $("#btn1").removeAttr("disabled").val('登录'); }, beforeSend: function () {//已向服务器发送请求,请求完成前 $("#btn1").attr("disabled", "disabled").val('登录中...'); },//按钮变成不可用,防止用户多次点击造成服务器负担 complete: function () {//请求完成后,可有可无 $("#btn1").removeAttr("disabled").val('登录'); } });
附: ajax与jQuery实现省市区三级联动:
html代码
<div>
<asp:DropDownList ID="DropDownList1" runat="server"></asp:DropDownList>
<asp:DropDownList ID="DropDownList2" runat="server"></asp:DropDownList>
<asp:DropDownList ID="DropDownList3" runat="server"></asp:DropDownList>
</div>
bind1($("#DropDownList1"), '0001', '1'); function bind1(drop, pc, key) { $.ajax({ url: "ajax/china.ashx", data: { "pcode": pc }, type: "post", dataType: "json", success: function (data) { drop.empty(); for (i in data) { var str = "<option value=\"" + data[i].code + "\">" + data[i].name + "</option>"; drop.append(str); } if (key == "1") { bind1($("#DropDownList2"), $("#DropDownList1").val(), '2'); } if (key == "2") { bind1($("#DropDownList3"), $("#DropDownList2").val(), '3'); } }, error: function () { alert('服务器连接失败!'); } }); } $("#DropDownList1").change(function () { bind1($("#DropDownList2"), $(this).val(), '2'); }); $("#DropDownList2").change(function () { bind1($("#DropDownList3"), $(this).val(), '3'); }); js代码
一般应用程序代码
using System; using System.Web; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; public class china : IHttpHandler { public void ProcessRequest (HttpContext context) { string pcode = context.Request["pcode"]; StringBuilder end = new StringBuilder(); int count = 0; end.Append("["); using (mydbDataContext con = new mydbDataContext()) { List<ChinaStates> clist = con.ChinaStates.Where(r => r.ParentAreaCode == pcode).ToList(); foreach (ChinaStates c in clist) { if (count > 0) end.Append(","); end.Append("{\"code\":\""+c.AreaCode+"\",\"name\":\""+c.AreaName+"\"}"); count++; } } end.Append("]"); context.Response.Write(end); context.Response.End(); } public bool IsReusable { get { return false; } } } china.ashx
浙公网安备 33010602011771号