标签:
1.ajax的基本使用
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html> <head> <title>1.html</title> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="this is my page"> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <script type="text/javascript" src="util.js"></script> <script type="text/javascript"> window.onload=function(){ document.getElementById("b1").onclick=function(){ var xhr = getXmlHttpRequest(); xhr.onreadystatechange=function(){ if(xhr.readyState==4){ if(xhr.status == 200){ alert("bbb"); } } } xhr.open("GET", "/Ajax_demo_00/servlet/ServletDemo1?time="+new Date().getTime()); xhr.send(null); } } </script> </head> <body> <input type="button" id="b1" value="测试ajax"> </body> </html>
util.js
function getXmlHttpRequest(){
var xmlHttp;
try {
// Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
}
catch (e) {
// Internet Explorer
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
alert("浏览器不支持");
}
}
}
return xmlHttp;
}
XmlHttpRequest详解:(重要)
1、XmlHttpRequest对象:
不同浏览器是不同的。
属性:
status:只读的。代表着服务器端返回的响应码(200)
statusText:只读的。代表着服务器端返回的响应吗描述。
readyState:只读的。代表着当前AJAX引擎处于的状态
0:代表XmlHttpRequest对象刚刚创建。
1:open已经调用(建立与服务器的链接),但是send()还没有调用,还没有发出请求。
2:send方法已经被调用。请求对象已经给了服务器端,但是还没有响应。
3:能够取到响应消息头,但是取不到相应的正文
4:响应结束,可以取到所有响应的内容。
responseText:只读的。代表着服务器端返回的文本。
responseXML:只读的。代表着服务器端返回的是XML的文档(Document)。
方法:
abort():终止异步请求。
getAllResponseHeaders():得到所有的响应消息头和值。就是一个字符串。
getResponseHeader(headerName):得到指定的响应消息头的值。返回一个字符串
open(String method,String url, boolean async):建立与服务器端的链接。async默认是true,异步请求。如果为false,就是同步请求。
send(“k1=v1&k2=v2”):向服务器端发送请求正文。get请求,传递null即可。
setRequestHeader(headerName,headerValue):向服务器端传递请求消息头。
事件:
onreadystatechange:对应一个函数。回调函数。每一次XmlHttpRequest对象的readyState的值发生变化,都会调用它指定的函数。
标签:
原文地址:http://www.cnblogs.com/jsnan/p/4616001.html