谈到ajax异步刷新技术,我之前感觉很高深,今天看了一下,大体上有一个了解,AJAX最大的应用就是我们要理解XMLHttpRequest这个对象。XMLHttpRequest可以提供不重新加载页面的情况下更新网页,在页面加载后在客户端向服务器请数 据, 在 页面加载后在服务器端接受数据,在后台向客户端发送数据。
关于ajax的详细叙述,可以参考这个博客:http://www.blogjava.net/tbwshc/archive/2012/07/24/383857.html
然后我贴出一些原始的ajax的例子,这样更方便了解ajax原理,解开他神奇的面纱,当然现在使用jQuery的ajax封装方法也非常方便。
例1:get请求
get.ashx:
<%@ WebHandler Language="C#" Class="_01_get" %> using System; using System.Web; public class _01_get : IHttpHandler { public void ProcessRequest (HttpContext context) { context.Response.ContentType = "text/plain"; //int m = 0; //int n = 5 / m; //System.Threading.Thread.Sleep(3000); context.Response.Write(DateTime.Now.ToString()); } public bool IsReusable { get { return false; } } }
get.htm:
<html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <script type="text/javascript"> //注意问题 //1 请求的路径中不要有中文 //2 注意大小写 //3 设置不读缓存 //4 区分readyState XMLHttpRequest的状态 和status http的状态码 //1 创建对象 var xhr = createXHR(); function createXHR() { var request; if (XMLHttpRequest) { request = new XMLHttpRequest(); } else { request = new ActiveXObject("Microsoft.XMLHTTP"); } return request; } function btn_click() { document.getElementById("d").innerHTML = "正在加载..."; //2 初始化 xhr.open("get","01-get.ashx?_="+ Math.random(),true); //设置请求头 不读缓存 //xhr.setRequestHeader("If-Modified-Since","0"); //3 注册事件 xhr.onreadystatechange = function () { //判断接收服务器的响应完成后 if (xhr.readyState == 4) { //判断服务器返回的状态码 if (xhr.status == 200) { //获取服务器返回的响应 //xhr.responseText //xhr.responseXML document.getElementById("d").innerHTML = xhr.responseText; } else { document.getElementById("d").innerHTML = "服务器内部错误"; } } } //4 发送请求 xhr.send(); } </script> </head> <body> <input type="button" value="get" /> <div id="d"></div> </body> </html>
例2:post请求提交保单
post.ashx:
<%@ WebHandler Language="C#" Class="_02_post" %> using System; using System.Web; public class _02_post : IHttpHandler { public void ProcessRequest (HttpContext context) { context.Response.ContentType = "text/plain"; string name = context.Request.Form["n"]; string pwd = context.Request.Form["p"]; if (name == "admin" && pwd == "admin") { context.Response.Write(1); } else { context.Response.Write(0); } } public bool IsReusable { get { return false; } } }
post.htm:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <script type="text/javascript"> //1 创建对象 var xhr = createXHR(); function createXHR() { var request; if (XMLHttpRequest) { request = new XMLHttpRequest(); } else { request = new ActiveXObject("Microsoft.XMLHTTP"); } return request; } function btn_click() { var name = my$("txtName").value; var pwd = my$("txtPwd").value; var data = "n=" + name + "&p=" + pwd; //2 xhr.open("post","02-post.ashx",true); //!------------------!注意 xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); //3 xhr.onreadystatechange = function () { if (xhr.readyState == 4) { if (xhr.status == 200) { var m = xhr.responseText; if (m == 1) { my$("msg").innerHTML = "登录成功"; } else { my$("msg").innerHTML = "登录失败"; } } else { my$("msg").innerHTML = "服务器内部错误"; } } } //4 xhr.send(data); } function my$(id) { return document.getElementById(id); } </script> </head> <body> <input type="text" id="txtName" /><br /> <input type="text" id="txtPwd" /><br /> <input type="button" value="Login" /> <span id="msg"></span> </body> </html>
例3:省市选择效果
pro.ashx:
<%@ WebHandler Language="C#" Class="_06_pro" %> using System; using System.Web; using System.Collections.Generic; using System.Text; public class _06_pro : IHttpHandler { public void ProcessRequest (HttpContext context) { context.Response.ContentType = "text/plain"; string s = context.Request.QueryString["pid"]; int pid; if (int.TryParse(s,out pid)) { //json形式的字符串 string json = GetDataByPId(pid); context.Response.Write(json); } else { context.Response.Write("[]"); } } private string GetDataByPId(int pid) { List<Data> list = GetAllDatas(); List<Data> wantedList = new List<Data>(); foreach (Data data in list) { if (data.Pid == pid) { wantedList.Add(data); } } //拼json形式的字符串 //[{ "Id": 1,"Name": "河北省","PId": 0 },// { "Id": 2,"Name": "日本省",// { "Id": 3,"Name": "台湾省","PId": 0 } // ] StringBuilder sb = new StringBuilder(); sb.Append("["); foreach (Data data in wantedList) { sb.Append("{ \"Id\": "+data.Id+",\"Name\": \""+data.Name+"\",\"PId\": "+data.Pid+" },"); } sb.Remove(sb.Length - 1,1); sb.Append("]"); return sb.ToString(); } /// <summary> /// 模拟从数据库中加载数据,返回泛型集合 /// </summary> /// <returns></returns> private List<Data> GetAllDatas() { List<Data> list = new List<Data>(); list.Add(new Data() { Id = 1,Name = "河北省",Pid = 0 }); list.Add(new Data() { Id = 2,Name = "台湾省",Pid = 0 }); list.Add(new Data() { Id = 3,Name = "日本省",Pid = 0 }); list.Add(new Data() { Id = 4,Name = "石家庄",Pid = 1 }); list.Add(new Data() { Id = 5,Name = "邯郸市",Pid = 1 }); list.Add(new Data() { Id = 6,Name = "邢台市",Pid = 1 }); list.Add(new Data() { Id = 7,Name = "高雄市",Pid = 2 }); list.Add(new Data() { Id = 8,Name = "台北",Pid = 2 }); list.Add(new Data() { Id = 9,Name = "台中",Pid = 2 }); list.Add(new Data() { Id = 10,Name = "东京",Pid = 3 }); list.Add(new Data() { Id = 11,Name = "冲绳",Pid = 3 }); list.Add(new Data() { Id = 12,Name = "大阪",Pid = 3 }); return list; } public bool IsReusable { get { return false; } } }
pro.htm:
<html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <script src=\'#\'" type="text/javascript"></script> <script type="text/javascript"> window.onload = function () { loadProvince(); } function loadProvince() { var province = my$("province"); //发送异步请求获取省的数据 ajax("get","06-pro.ashx?pid=0",null,function (s) { //把字符串转化成对象 var array = eval(s); for (var i = 0; i < array.length; i++) { var json = array[i]; var option = document.createElement("option"); option.innerHTML = json.Name; option.value = json.Id; province.appendChild(option); } //当省加载完,再加载市 loadCity(); },function () { alert("服务器内部错误"); }); } function loadCity() { var pid = my$("province").value; var city = my$("city"); //清空下拉框 city.innerHTML = ""; ajax("get","06-pro.ashx?pid=" + pid,function (s) { //把字符串转化成对象 var array = eval(s); for (var i = 0; i < array.length; i++) { var json = array[i]; var option = document.createElement("option"); option.innerHTML = json.Name; option.value = json.Id; city.appendChild(option); } },function () { alert("服务器内部错误"); }); } </script> </head> <body> <select id="province" onchange="loadCity()"> </select> <select id="city"> </select> </body> </html>
自己封装的ajax:
function my$(id) { return document.getElementById(id); } var xhr = createXHR(); function createXHR() { var request; if (XMLHttpRequest) { request = new XMLHttpRequest(); } else { request = new ActiveXObject("Microsoft.XMLHTTP"); } return request; } function ajax(method,url,data,fnSuccess,fnError) { xhr.open(method,true); if (method == "post") { //!------------------!注意 xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); } xhr.onreadystatechange = function () { if (xhr.readyState == 4) { if (xhr.status == 200) { var s = xhr.responseText; fnSuccess(s); } else { fnError(); } } } xhr.send(data); }
这里要感谢刘兄的指导,在此鸣谢!
==================== 迂者 丁小未 CSDN博客专栏=================
MyBlog:http://blog.csdn.net/dingxiaowei2013 MyQQ:1213250243
Unity QQ群:858550 cocos2dx QQ群:280818155
======================相互学习,共同进步===================
转载请注明出处:http://blog.csdn.net/dingxiaowei2013/article/details/17130553