本文介绍关于XMLHttpRequest对象的基础知识(基于规范化的属性和方法),更深入的探讨在之后的文章中作为二级文章(“XMLHttpRequest对象详解二”,“XMLHttpRequest对象详解之使用”)更新,供那些想深入了解的人参考。
提示:在看本文时,可以参考昨天的 ajax 源码深入理解,文章可从历史记录中查找
XMLHttpRequest 对象还没有标准化,它有一些规范化(浏览器都已包括)和非规范化(部分浏览器实现)的属性和方法。得到了所有现代浏览器较好的支持,在IE5和IE6中必须使用特定于IE的ActiveXObject()构造函数。附图谷歌浏览器和火狐浏览器的对象属性。
概念:
XMLHttpRequest is an API that provides client functionality for transferring data between a client and a server.
XMLHttpRequest对象用于在后台与服务器交互数据。
It provides an easy way to retrieve data from a URL without having to do a full page refresh. This enables a Web page to update just a part of the page without disrupting what the user is doing.
能够在不重新加载页面的情况下更新网页,不干扰用户的操作。
XMLHttpRequest can be used to retrieve any type of data, not just XML, and it supports protocols other than HTTP(including file and ftp).
XMLHttpRequest对象提供了对HTTP协议的完全访问,包括做出POST和HEAD请求以及普通的get请求的能力。
XMLHttpRequest可以同步或异步地返回web服务器的相应,并且能够以文本或者一个DOM文档的形式返回内容。
可以接收任何形式的文本文档。
构造方法:
The XMLHttpRequest() constructor initiates an XMLHttpRequest. It must be called before any other method calls.
varmyRequest= new XMLHttpRequest();
该方法有两个非标准化的参数:Boolean mozAnon, Boolean mozSystem.
可参考网址:
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/XMLHttpRequest
参数:
1. readyState -- HTTP请求的状态
当一个XMLHttpRequest初次创建时,这个属性的值从0开始,直到收到完整的HTTP相应,这个值增加到4。
readyState的值不会递减,除非当一个请求在处理过程中的时候调用了abort()或open()方法,每次这个属性的值增加的时候,都会触发onReadyStateChange事件句柄。
2. onreadystatechange -- 事件句柄
XMLHttpRequest.onreadystatechange = callback;
每次readyState属性状态改变的时候调用该函数,当readyState为3时,可能调用多次。
3. responseType
它是响应类型,值包括"arraybuffer", "blob", "document", "json", "text"。 可以由自己指定。If an empty string is set as the value of responseType, it is assumed as type "text".
在Worker环境下设置为document会被忽略。
设置为某一特定值时,应 确保该服务器发送的是一个兼容的响应。如果返回的是不兼容的responseType,the value of response will be null.
同步的请求设置responseType将抛出一个UnvalidAccessError异常。
4. response
返回响应体,可以是ArrayBuffer, Blob, Document, JavaScript Object or a DOMString. 取决于responseType的值。如果请求不完整或者不成功,response is none。
注:当readyState为3时, response可以是不完整信息。
5. status
由服务器返回的HTTP状态代码,
http://www.w3school.com.cn/tags/html_ref_httpmessages.asp
当readyState小于3时,读取这一属性会导致一个异常。
6. statusText
这个属性用名称而不是数字制定了请求的HTTP状态代码。例如: status=200时,statusText="OK"
方法:
8. Non-standard methods. 例如:init(), openRequest(), sendAsBinary().
更多关于XMLHttpRequest的权威知识请查看一下链接:
附图
谷歌浏览器下的对象属性:
火狐浏览器下的对象属性: