一. IE7以后对xmlHttpRequest 对象的创建在不同浏览器上是兼容的。
下面的方法是考虑兼容性的,实际项目中一般使用Jquery的ajax请求,可以不考虑兼容性问题。
function getHttpObject() { var xhr=false; if (windows.XMLHttpRequest) xhr=new XMLHttpRequest(); else if (window.ActiveXObject) { xhr=new ActiveXObject("Microsoft.XMLHttp"); } return xhr; }
二. XMLHttpRequest的属性及方法
1、方法 描述
abort() 停止当前请求
getAllResponseHeaders() 把HTTP请求的所有响应首部作为键/值对返回
getResponseHeader(“header”) 返回指定键的首部串值
open(“method”,”url”) 建立对服务器的调用,Method可以是GET,POST或PUT,URL可以是相对或绝对URL
send(content) 向服务器发送请求
setRequestHeader(“header”,”value”) 把指定首部设置为所提供的值。在设置任何首部之前必须调用open()
2、属性 描述
onreadystatechange 每个状态改变都会触发,通常会调用一个javascript函数
readyState 请求的状态,5个值; 0:为初始化,1:正在加载;2:已经加载,3:交互中,4:完成
responseText 服务器的响应,表示为字符串
responseXML 服务器的响应,表示为XML,可以解析为DOM对象
status 服务器的HTTP状态码(200:ok,304:not modified,404:Not Found 等)
statusText Http状态码的相应文本(ok或Not Found)
3、手写一个Ajax请求的例子:
$(function(){ $("#id").onclick(tunction(){ var request=new XMLHttpRequest(); var url="http://www.baidu.com"; var method="GET"; request.open(method,url); request.send(null); request.onreadystatechange=function(){ if (request.readyState==4&&(request.status==200 || request.status==304)) alert (request.reponseText);