1. XHR 对象
在使用XHR对象时, 要调用的第一个方法是 open(), 3个参数: 要发送请求的了类型("get", "post" ) 请求的URL 和 表示是否异步发送请求的布尔值
xhr.open( "get", "example.php", false ) ; // URL 相对于执行代码的当前页面( 当然也可以使用绝对路径 ) , 调用 open() 方法并不会真正发送请求, 而只是启动一个请求准备.
( 只能向一个域中使用相同端口和协议的URL发送请求 )
xhr.open( "get", "example.php", false ) ;
xhr.send( null ) ; // 参数是向服务器发送数据
XHR 对象属性 :
1) responseText : 作为响应主题被返回的文本.
2) responseXML : 如果响应内容类型是 "text/xml" 或 "application/xml" , 这个属性中将保存包含着响应数据的 XML DOM 文档.
3) status : 响应 HTTP 状态
4) statusText : HTTP状态说明
先看status看是否响应成功, 一般成功标志是200,此时,responseText属性内容已经就绪,而且responseXML也能够访问了 ( status 304 表示请求资源并没有被修改 )
建议通过 status 做判断. 而对于非 XML数据而言, responseXML属性的值将为 null .
XHR的 readyState属性 0 未初始化(没有open) 1启动 已open()尚未send(), 2 发送 已经send() 但尚未接收到响应, 3 接收 4完成
onreadystatechange 事件 ( 通常只对 4 完成的状态感兴趣 )
var xhr = createXHR() ;
xhr.onreadystateChange = function() {
if ( xhr.readyState == 4 ){
if ( ( xhr.status >= 200 && xhr.status <300 ) || xhr.status == 304 ) {
alert ( xhr.responseText ) ;
} else {
alert( "Request was unsuccessful : " + xhr.status ) ;
}
}
} ;
xhr.open ( "get", "example.txt", true ) ;
xhr.send( null ) ;
xhr.abort() ; // XHR 对象进行解引用操作