Ajax基础

一、简介

AJAX = Asynchronous JavaScript and XML(异步的 JavaScript 和 XML)。

AJAX 是一种用于创建快速动态网页的技术。

AJAX通过在后台与服务器进行少量数据交换,AJAX 可以使网页实现异步更新。

AJAX 不是新的编程语言,而是一种使用现有标准的新方法。

AJAX 最大的优点是在不重新加载整个页面的情况下,可以与服务器交换数据并更新部分网页内容。

AJAX 不需要任何浏览器插件,但需要用户允许JavaScript在浏览器上执行。

AJAX 工作原理

二、AJAX创建

以User表为例,列表展示数据,当点击按钮时展示数据

1.新建一个LINQ to SQL 类(Web.dbml),将User表和Nation表拉到类中

 数据扩展

2.新建一个纯HTML界面(HtmlPage.html)和一个一般处理程序(userajax.ashx)

(1)body内代码

复制代码
 1  <table id="tb1" style=" text-align: center; width: 100%;">
 2     <thead>
 3         <tr style="color: #ff6a00;">
 4             <td>用户名</td>
 5             <td>密码</td>
 6             <td>昵称</td>
 7             <td>性别</td>
 8             <td>生日</td>
 9             <td>年龄</td>
10             <td>民族</td>
11         </tr>
12     </thead>
13     <tbody>
14     </tbody>
15     </table>
16     <input type="button" value="加载" id="btn1" />
复制代码

(2)js代码部分

复制代码
 1 <script>
 2     //点击加载按钮
 3     $("#btn1").click(function () {
 4         //编写ajax语句,将数据提交到某个服务端去
 5         $.ajax({
 6             url: "ajax/userajax.ashx",//将数据要提交到哪个服务端
 7             data: {},//将什么数据提交到服务端去,{}内基本格式为"key":"要传的数据"
 8             type: "post",//用什么样的方式将数据提交过去
 9             dataType: "json",//返回一个什么样的数据类型
10             //请求完成
11             success: function (data) {
12                 $("#tb1 tbody").empty();//清空tbody
13                 for (i in data) {
14                     var str = "<tr style=\"\">";
15                     str += "<td>" + data[i].username + "</td>";
16                     str += "<td>" + data[i].password + "</td>";
17                     str += "<td>" + data[i].nickname + "</td>";
18                     str += "<td>" + data[i].sex + "</td>";
19                     str += "<td>" + data[i].birthday + "</td>";
20                     str += "<td>" + data[i].age + "</td>";
21                     str += "<td>" + data[i].nation + "</td>";
22                     str += "</tr>";
23                     $("#tb1 tbody").append(str);
24                 }
25             },//success
26             //请求失败
27             error: function () {
28                 alert('服务器连接失败!!!');
29             }
30         });//ajax
31     });//btn1.click
32 </script>
复制代码

(3)userajax.ashx内代码

复制代码
 1 <%@ WebHandler Language="C#" Class="userajax" %>
 2 
 3 using System;
 4 using System.Web;
 5 using System.Collections;
 6 using System.Collections.Generic;
 7 using System.Linq;
 8 using System.Text;
 9 
10 public class userajax : IHttpHandler
11 {
12 
13     public void ProcessRequest(HttpContext context)
14     {
15         //有数据接收时,用context.Request["key"];将ajax传过来的数据取出来
16         int count = 0;//前面是否有数据
17         string end = "[";//创建json对象,设置默认值,基本格式为{"key":"value","":"","":""},有多条时用[]括住,每条之间用,隔开
18         using (WebDataContext con = new WebDataContext())
19         {
20             List<User> ulist = con.User.ToList();
21             foreach (User u in ulist) {
22                 //前面有数据
23                 if (count>0) {
24                     end += ",";
25                 }
26                 end += "{\"username\":\""+u.UserName+"\",\"password\": \""+u.PassWord+"\",\"nicknane\":\""+u.NickName+"\",\"sex\": \""+u.SexStr+"\",\"birthday\": \""+u.BirStr+"\",\"age\":\""+u.Age+"\",\"nation\":\""+u.NationName+"\" }";
27                 count++;
28             }
29         }
30         end += "]";
31             context.Response.Write(end);
32             context.Response.End();
33      
34     }
35 
36     public bool IsReusable
37     {
38         get
39         {
40             return false;
41         }
42     }
43 
44 }
复制代码

三、json与xml

xml和json的作用:在不同语言之间进行数据传递

最早使用的数据类型是 xml

优势:

A.格式统一,符合标准;
B.容易与其他系统进行远程交互,数据共享比较方便。
劣势:
1、代码量较大
2、结构不清晰
3、解析起来麻烦

现在使用的数据类型是 json
优势:
1、结构清晰
2、类似于面向对象的解析方式

四、ajax完整结构

复制代码
 1  //编写ajax语句,将数据提交到某个服务端去
 2         $.ajax({
 3             url: "ajax/Login.ashx",//将数据要提交到哪个服务端
 4             data: { "un": $("#txt_uname").val().trim(), "pwd": $("#txt_pwd").val() },//将什么数据提交到服务端去,{}内基本格式为"key":"要传的数据"
 5             type: "post",//用什么样的方式将数据提交过去
 6             dataType: "json",//返回一个什么样的数据类型
 7             success: function (data) {//请求完成
 8                 if (data.has == '1') {
 9                     $("#btn1").attr("disabled", "disabled").val('跳转中...');
10                     window.setTimeout(function () {
11                         window.location.href = "HtmlPage2.html";
12                     }, 3000);
13                 }
14                 else {
15                     $("#sp1").text("用户名密码输入错误!");
16                     $("#btn1").removeAttr("disabled").val('登录');
17                 }
18             },
19             error: function () {//服务器连接错误
20                 $("#sp1").text("服务器连接失败!");
21                 $("#btn1").removeAttr("disabled").val('登录');
22             },
23             beforeSend: function () {//已向服务器发送请求,请求完成前
24                 $("#btn1").attr("disabled", "disabled").val('登录中...');
25             },
26             complete: function () {//请求完成后,可有可无
27                 $("#btn1").removeAttr("disabled").val('登录');
28             }
29 
30 
31         });
复制代码

附: 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>
HTML代码
 1 bind1($("#DropDownList1"), '0001', '1');
 2     function bind1(drop, pc, key) {
 3         $.ajax({
 4             url: "ajax/china.ashx",
 5             data: { "pcode": pc },
 6             type: "post",
 7             dataType: "json",
 8             success: function (data) {
 9                 drop.empty();
10                 for (i in data) {
11                     var str = "<option value=\"" + data[i].code + "\">" + data[i].name + "</option>";
12                     drop.append(str);
13                 }
14                 if (key == "1")
15                     {
16                     bind1($("#DropDownList2"), $("#DropDownList1").val(), '2');
17                 }
18                 if (key == "2") {
19                     bind1($("#DropDownList3"), $("#DropDownList2").val(), '3');
20                 }
21 
22             },
23             error: function () {
24                 alert('服务器连接失败!');
25             }
26         });
27     }
28     $("#DropDownList1").change(function () {
29         bind1($("#DropDownList2"), $(this).val(), '2');
30     });
31 
32     $("#DropDownList2").change(function () {
33         bind1($("#DropDownList3"), $(this).val(), '3');
34     });
js代码
 1 using System;
 2 using System.Web;
 3 using System.Collections;
 4 using System.Collections.Generic;
 5 using System.Linq;
 6 using System.Text;
 7 public class china : IHttpHandler {
 8     
 9     public void ProcessRequest (HttpContext context) {
10         string pcode = context.Request["pcode"];
11         StringBuilder end = new StringBuilder();
12         int count = 0;
13 
14         end.Append("[");
15         using (mydbDataContext con = new mydbDataContext())
16         {
17             List<ChinaStates> clist = con.ChinaStates.Where(r => r.ParentAreaCode == pcode).ToList();
18 
19             foreach (ChinaStates c in clist)
20             {
21                 if (count > 0)
22                     end.Append(",");
23                 
24                 end.Append("{\"code\":\""+c.AreaCode+"\",\"name\":\""+c.AreaName+"\"}");
25                 count++;
26             }
27         }
28 
29         end.Append("]");
30         context.Response.Write(end);
31         context.Response.End();
32     }
33  
34     public bool IsReusable {
35         get {
36             return false;
37         }
38     }
39 
40 }
china.ashx

 

posted @ 2016-12-14 15:35  C.E  阅读(145)  评论(0编辑  收藏  举报