Ajax-XMLHttpRequest总结
Ajax = Asynchronous JavaScript and XML(异步的JavaScript和XML)
个人理解:Ajax是以XMLHttpRequest为核心,与服务器交换数据,实现部分更新网页。
创建XMLHttpRequest对象
所有现代浏览器(IE7+、Firefox、Chrome、Safari 以及 Opera)均内建 XMLHttpRequest 对象。
老版本的Internet Explorer(IE5和IE6)使用ActiveX对象。
为了应对所有的现代浏览器,包括 IE5 和 IE6,请检查浏览器是否支持 XMLHttpRequest 对象。如果支持,则创建 XMLHttpRequest 对象。如果不支持,则创建 ActiveXObject:
1 var xmlhttp; 2 if (window.XMLHttpRequest) 3 {////////// code for IE7+, Firefox, Chrome, Opera, Safari 4 xmlhttp=new XMLHttpRequest(); 5 } 6 else 7 {////////// code for IE6, IE5 8 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 9 }
向服务器发送请求
使用XMLHttpRequest对象的open()和send()方法:
1 xmlhttp.open("GET","test1.txt",true); 2 xmlhttp.send();
GET 还是 POST?
与 POST 相比,GET 更简单也更快,并且在大部分情况下都能用。
然而,在以下情况中,请使用 POST 请求:
- 无法使用缓存文件(更新服务器上的文件或数据库)
- 向服务器发送大量数据(POST 没有数据量限制)
- 发送包含未知字符的用户输入时,POST 比 GET 更稳定也更可靠
如果通过GET方法发送信息,请向URL添加信息:
1 xmlhttp.open("GET","demo_get2.asp?fname=Bill&lname=Gates",true); 2 xmlhttp.send();
如果需要像HTML表单那样POST数据,请使用setRequestHeader()来添加HTTP头。然后在send()方法中规定需要发送的数据:
xmlhttp.open("POST","ajax_test.asp",true); xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded"); xmlhttp.send("fname=Bill&lname=Gates");
可以异步请求,也可以同步请求
异步:
1 xmlhttp.onreadystatechange=function() 2 { 3 if (xmlhttp.readyState==4 && xmlhttp.status==200) 4 { 5 document.getElementById("myDiv").innerHTML=xmlhttp.responseText; 6 } 7 } 8 xmlhttp.open("GET","test1.txt",true); 9 xmlhttp.send();
同步:
1 xmlhttp.open("GET","test1.txt",false); 2 xmlhttp.send(); 3 document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
Ajax的api文档
Demonstration
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 2 <html xmlns="http://www.w3.org/1999/xhtml"> 3 <head> 4 <title>使用XMLHttpRequest对象进行Ajax请求</title> 5 <script type="text/javascript"> 6 function getData() { 7 var xmlhttp; 8 if (window.XMLHttpRequest) { 9 xmlhttp = new XMLHttpRequest(); 10 } else { 11 xmlhttp = new ActiveXObject("microsoft.XMLHTTP"); 12 } 13 if (xmlhttp != null) { 14 xmlhttp.onreadystatechange = function () { 15 if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { 16 document.getElementById("div_data").innerHTML = xmlhttp.responseText; 17 } 18 } 19 xmlhttp.open("GET", "Handler1.ashx", true); 20 xmlhttp.send(null); 21 } else { 22 alert("Your browser does not support XMLHTTP."); 23 } 24 } 25 </script> 26 </head> 27 <body> 28 <input type="button" value="getData" onclick="getData()" /> 29 <div id="div_data"> 30 </div> 31 </body> 32 </html>
1 using System.Web; 2 3 namespace Ajax_Demo 4 { 5 /// <summary> 6 /// Handler1 的摘要说明 7 /// </summary> 8 public class Handler1 : IHttpHandler 9 { 10 11 public void ProcessRequest(HttpContext context) 12 { 13 context.Response.ContentType = "text/plain"; 14 context.Response.Write("Hello World"); 15 } 16 17 public bool IsReusable 18 { 19 get 20 { 21 return false; 22 } 23 } 24 } 25 }