JS使用XMLHttpRequest实现ajax请求

XMLHttpRequest是一个JavaScript对象,它最初由微软设计,随后被 Mozilla、Apple和Google采纳。如今,该对象已经被 W3C组织标准化。通过它,你可以很容易的取回一个URL上的资源数据。尽管名字里有XML, 但XMLHttpRequest 可以取回所有类型的数据资源,并不局限于XML。而且除了HTTP ,它还支持fileftp 协议。

创建一个 XMLHttpRequest 实例, 可以使用如下语句:

var req = new XMLHttpRequest();

方法概述

void abort();
DOMString getAllResponseHeaders();
DOMString? getResponseHeader(DOMString header);
void open(DOMString method, DOMString url, optional boolean async, optional DOMString? user, optional DOMString? password);
void overrideMimeType(DOMString mime);
void send();
void send(ArrayBuffer data);
void send(Blob data);
void send(Document data);
void send(DOMString? data);
void send(FormData data);
void setRequestHeader(DOMString header, DOMString value);
非标准方法
[noscript] void init(in nsIPrincipal principal, in nsIScriptContext scriptContext, in nsPIDOMWindow ownerWindow);
[noscript] void openRequest(in AUTF8String method, in AUTF8String url, in boolean async, in AString user, in AString password);
void sendAsBinary(in DOMString body);

属性

Attribute Type Description
onreadystatechange Function?

一个JavaScript函数对象,当readyState属性改变时会调用它。回调函数会在user interface线程中调用。

警告: 不能在本地代码中使用. 也不应该在同步模式的请求中使用.

readyState unsigned short 请求的五种状态
状态 描述
0 UNSENT (未打开) open()方法还未被调用.
1 OPENED  (未发送) send()方法还未被调用.
2 HEADERS_RECEIVED (已获取响应头) send()方法已经被调用, 响应头和响应状态已经返回.
3 LOADING (正在下载响应体) 响应体下载中; responseText中已经获取了部分数据.
4 DONE (请求完成) 整个请求过程已经完毕.
状态 描述
0 UNSENT (未打开) open()方法还未被调用.
1 OPENED  (未发送) send()方法还未被调用.
2 HEADERS_RECEIVED (已获取响应头) send()方法已经被调用, 响应头和响应状态已经返回.
3 LOADING (正在下载响应体) 响应体下载中; responseText中已经获取了部分数据.
4 DONE (请求完成) 整个请求过程已经完毕.
状态 描述
0 UNSENT (未打开) open()方法还未被调用.
1 OPENED  (未发送) send()方法还未被调用.
2 HEADERS_RECEIVED (已获取响应头) send()方法已经被调用, 响应头和响应状态已经返回.
3 LOADING (正在下载响应体) 响应体下载中; responseText中已经获取了部分数据.
4 DONE (请求完成) 整个请求过程已经完毕.
状态 描述
0 UNSENT (未打开) open()方法还未被调用.
1 OPENED  (未发送) send()方法还未被调用.
2 HEADERS_RECEIVED (已获取响应头) send()方法已经被调用, 响应头和响应状态已经返回.
3 LOADING (正在下载响应体) 响应体下载中; responseText中已经获取了部分数据.
4 DONE (请求完成) 整个请求过程已经完毕.
response varies 响应实体的类型由 responseType 来指定, 可以是 ArrayBuffer, Blob, Document, JavaScript 对象 (即 “json”), 或者是字符串。如果请求未完成或失败,则该值为 null。
responseText DOMString 此次请求的响应为文本,或是当请求未成功或还未发送时为 null。只读。
responseXML Document? 本次请求的响应是一个 Document 对象,如果是以下情况则值为 null:请求未成功,请求未发送,或响应无法被解析成 XML 或 HTML。当响应为text/xml 流时会被解析。当 responseType 设置为”document”,并且请求为异步的,则响应会被当做 text/html 流来解析。只读.

 

注意: 如果服务器不支持 text/xml Content-Type 头,你可以使用 overrideMimeType() 强制 XMLHttpRequest 将响应解析为 XML。
status unsigned short 该请求的响应状态码 (例如, 状态码200 表示一个成功的请求).只读.
statusText DOMString 该请求的响应状态信息,包含一个状态码和原因短语 (例如 “200 OK“). 只读.
upload XMLHttpRequestUpload 可以在 upload 上添加一个事件监听来跟踪上传过程。
withCredentials boolean 表明在进行跨站(cross-site)的访问控制(Access-Control)请求时,是否使用认证信息(例如cookie或授权的header)。 默认为 false。 注意: 这不会影响同站(same-site)请求.

非标准属性

AttributeTypeDescription
channelnsIChannelThe channel used by the object when performing the request. This is null if the channel hasn’t been created yet. In the case of a multi-part request, this is the initial channel, not the different parts in the multi-part request. Requires elevated privileges to access; 只读.
mozBackgroundRequestbooleanIndicates whether or not the object represents a background service request. If true, no load group is associated with the request, and security dialogs are prevented from being shown to the user. Requires elevated privileges to access.

 

In cases in which a security dialog (such as authentication or a bad certificate notification) would normally be shown, the request simply fails instead.

mozResponseArrayBuffer 已废弃 Gecko 6ArrayBufferThe response to the request, as a JavaScript typed array. This is NULL if the request was not successful, or if it hasn’t been sent yet. 只读
multipartbooleanIndicates whether or not the response is expected to be a stream of possibly multiple XML documents. If set to true, the content type of the initial response must be multipart/x-mixed-replace or an error will occur. All requests must be asynchronous.

 

This enables support for server push; for each XML document that’s written to this request, a new XML DOM document is created and the onload handler is called between documents.

注意: When this is set, the onload handler and other event handlers are not reset after the first XMLdocument is loaded, and the onload handler is called after each part of the response is received.

方法

abort()

如果请求已经被发送,则立刻中止请求.

getAllResponseHeaders()

DOMString getAllResponseHeaders();

返回所有响应头信息(响应头名和值), 如果响应头还没接受,则返回null. 注意: For multipart requests, this returns the headers from the current part of the request, not from the original channel.

getResponseHeader()

DOMString? getResponseHeader(DOMString header);

返回指定的响应头的值, 如果响应头还没被接受,或该响应头不存在,则返回null。

open()

初始化一个请求. 该方法用于JavaScript代码中;如果是本地代码, 使用 openRequest()方法代替.

注意: Calling this method an already active request (one for which open()or openRequest()has already been called) is the equivalent of calling abort().

void open(
   DOMString method,
   DOMString url,
   optional boolean async,
   optional DOMString user,
   optional DOMString password
);
参数
method
请求所使用的HTTP方法; 例如 “GET”, “POST”, “PUT”, “DELETE”等. 如果下个参数是非HTTP(S)的URL,则忽略该参数.
url
该请求所要访问的URL
async
An optional boolean parameter, defaulting to true, indicating whether or not to perform the operation asynchronously. If this value is false, the send()method does not return until the response is received. If true, notification of a completed transaction is provided using event listeners. This must be true if the multipart attribute is true, or an exception will be thrown.
user
用户名,可选参数,为授权使用;默认参数为空string.
password
密码,可选参数,为授权使用;默认参数为空string.

overrideMimeType()

Overrides the MIME type returned by the server. This may be used, for example, to force a stream to be treated and parsed as text/xml, even if the server does not report it as such.This method must be called before send().

void overrideMimeType(DOMString mimetype);

send()

发送请求. 如果该请求是异步模式(默认),该方法会立刻返回. 相反,如果请求是同步模式,则直到请求的响应完全接受以后,该方法才会返回.

注意: 所有相关的事件绑定必须在调用send()方法之前进行.
void send();
void send(ArrayBuffer data);
void send(Blob data);
void send(Document data);
void send(DOMString? data);
void send(FormData data);

注意

If the data is a Document, it is serialized before being sent. When sending a Document, versions of Firefox prior to version 3 always send the request using UTF-8 encoding; Firefox 3 properly sends the document using the encoding specified by body.xmlEncoding, or UTF-8 if no encoding is specified.

If it’s an nsIInputStream, it must be compatible with nsIUploadChannel‘s setUploadStream()method. In that case, a Content-Length header is added to the request, with its value obtained using nsIInputStream‘s available()method. Any headers included at the top of the stream are treated as part of the message body. The stream’s MIMEtype should be specified by setting the Content-Type header using the setRequestHeader()method prior to calling send().

setRequestHeader()

给指定的HTTP请求头赋值.在这之前,你必须确认已经调用 open() 方法打开了一个url.

void setRequestHeader(
   DOMString header,
   DOMString value
);

参数

header
将要被赋值的请求头名称.
value
给指定的请求头赋的值.

非标准方法

init()

在 C++代码中初始化一个XHR对象.

警告: 该方法不能在 JavaScript 代码中使用.
[noscript] void init(
   in nsIPrincipal principal,
   in nsIScriptContext scriptContext,
   in nsPIDOMWindow ownerWindow
);
参数
principal
主要用于请求;不可以为null.
scriptContext
请求上下文;不可以为null.
ownerWindow
和窗口相关请求; 可能为null.

openRequest()

初始化一个请求. 这个方法用于本地代码; 如果用JavaScript 代码来初始化请求, 使用 open()代替. 看文档open().

sendAsBinary()

发送二进制数据 的send()方法变种.

void sendAsBinary(
   in DOMString body
);
参数
body
The request body as a DOMstring. This data is converted to a string of single-byte characters by truncation (removing the high-order byte of each character).

注意

  • By default, Firefox 3 limits the number of XMLHttpRequest connections per server to 6 (previous versions limit this to 2 per server). Some interactive web sites may keep an XMLHttpRequest connection open, so opening multiple sessions to such sites may result in the browser hanging in such a way that the window no longer repaints and controls don’t respond. This value can be changed by editing the network.http.max-persistent-connections-per-server preference in about:config.
  • From Gecko 7.0 headers set by setRequestHeader() are sent with the request when following a redirect. Previously these headers would not be sent.
  • XMLHttpRequest is implemented in Gecko using the nsIXMLHttpRequest, nsIXMLHttpRequestEventTarget, and nsIJSXMLHttpRequest interfaces.

Events

onreadystatechange as a property on the xhr object is supported in all browsers.

Since then, a number of additional event handlers were implemented in various browsers (onload, onerror, onprogress, etc.). These are supported in Firefox. In particular, see nsIXMLHttpRequestEventTarget and Using XMLHttpRequest.

More recent browsers, including Firefox, also support listening to the XMLHttpRequest events via standard addEventListener APIs in addition to setting on* properties to a handler function.

浏览器兼容性Edit

  • Desktop
  • Mobile
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support (XHR1)11.05 (via ActiveXObject)
7 (XMLHttpRequest)
(Yes)1.2
send(ArrayBuffer)99?11.60?
send(Blob)73.6?12?
send(FormData)64?12?
response1061011.60?
responseType = ‘arraybuffer’1061011.60?
responseType = ‘blob’1961012?
responseType = ‘document’1811未实现未实现未实现
responseType = ‘json’未实现10未实现12未实现
Progress Events73.51012?
withCredentials33.510124

你可能还喜欢下面这些文章

使用php curl 的并发能力可以做什么

在php中,没有多线程让编程变得简单。但在一些需要并发提升性能的场景下,显得有些无能为力,比如发起一些http请求。但好在curl扩展可以让我们“并发”去请求网络资源。利用这个特点,我们能做很多有趣的事情。最基础的,并发请求网络资源,提升处理速度。并发访问代码<?phpclass ConcurrencyHTTP { private $_requests; private $_callbacks; private $_currentIndex = 0; public function get($url, $header = array(), $timeout = 3

赞赏

微信赞赏支付宝赞赏

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注