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

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

ajax的核心,好好认识一下XMLHttpRequest

相信包括在我的绝大多数人都用jQuery的$.get(),$.post(),$.ajax()方法用的很爽了,关于其原生的请求却很少去发掘,很多时候(比如用html5开发app的时候),我并不再需要jQuery,弄明白XMLHttpRequest用原生的就能很好的处理ajax了。首先,由于我的js是通过jQuery入门的,所以才会有这篇文章。从new一个对象开始var xmlhttp = new XMLHttpRequest();之后的请求,读取,出错等等各种处理都在xmlhttp这个对象里面啦第一个GET请求get请求简单,最适合入门操作啦。之前new了一个xmlhttp对象,这次我们就要对它

使用sublime+platuml高效画图

程序员难免要经常画流程图,状态图,时序图等。以前经常用 visio 画,经常为矩形画多大,摆放在哪等问题费脑筋。有时候修改文字后,为了较好的显示效果不得不再去修改图形。今天介绍的工具是如何使用 Sublime + PlantUML 的插件画流程图,状态图,时序图等。这是一种程序员看了就会爱上的画图方式:自然,高效。什么是 PlantUMLPlantUML 是一个画图脚本语言,用它可以快速地画出:时序图流程图用例图状态图组件图简单地讲,我们使用 visio 画图时需要一个一个图去画,但使用 PlantUML 只需要用文字表达出图的内容,然后就可以直接生成图片。看一个最简单的例子:软件安装这些软件

gcc/g++编译参数详解

编译步骤gcc 与 g++ 分别是 gnu 的 c & c++ 编译器。gcc/g++ 在执行编译工作的时候,总共需要4步:预处理,生成 .i 的文件将预处理后的文件转换成汇编语言, 生成文件 .s 有汇编变为目标代码(机器代码)生成 .o 的文件连接目标代码, 生成可执行程序 参数详解-x language filename参数含义为指定文件所使用的语言。根据约定,C语言的后缀名称为".c",而 C++ 的后缀名为".cpp"或".cc",但如果你的源代码后缀不约定的那几种,那么需要使用-x参数来指定文件所使用的语言。这个参数对他后面的文件名都起作用。 可以使用的参数吗有下面的这些:

Go入门:六、常用标准库

这是我的Go学习的第六篇笔记,也是Go入门的最后一篇笔记。在大多数语言中,了解了变量和数据类型,流程控制,函数,面向对象,再加上标准库,就可以用这门语言去写一些项目了。首先让我想想,在工作中通常会用语言频繁处理什么问题或者处理什么数据?最常见的应该是各种字符串操作,日期和时间,读写文件、socket等IO相关的操作!字符串处理 — StringsString提供了一组处理字符串的操作,常用的有:判断一个字符串是否在另一个字符串中分割字符串为[]string和组合[]string为一个字符串字符串替换...太多了,就不一一列举了,这里列出一些常用的字符串操作。字符串判断字符串分割与合并字符串转换

php的file_get_contents()的高级用法

读取文件,读取网页,file_get_contents总是首选。既简单,又高效。读取网页: $content = file_get_contents("http://imhuchao.com")这里要说的是file_get_contents的一些"高级"的用法,平时大概用不上。file_get_contents可以用来发送post请求,设定超时时间等等,不弱于curl。函数说明是这样子的string file_get_contents ( string $filename ]]] )其中第三个参数$context能够让file_get_content发送post请求,控制超时等功能先看一个简单

C++动态内存管理

C++中,动态内存管理是通过一对运算符来完成:new 和 delete。new操作符在内存中为对象分配空间并返回一个指向该对象的指针,delete接收一个动态对象的指针,销毁该对象,并释放与之相关的内存。手动管理内存看起来只有这两个操作,似乎很轻松,但实际上这是一件非常繁琐的事情,分配了内存但没有释放内存的场景发生的概率太大了!回想一下,你有多少次打开抽屉却没关上,拿出来的护肤品擦完脸之后却忘了放回去,吃完饭却忘了洗碗。类似这种没有收尾的事情我做的太多了。(以上这些都是在实际生活中我爱人批评我的点)我连这种明面上的事情都能忘记收尾,何况分配内存!所以为了世界和平,我放弃了手动管理内存。好在C+

ftp命令大全详解

来熟悉熟悉ftp命令,对于服务器之间的文件传输太有用啦,不会怎么能行呢!先来看看基础的命令,包括了连接,列出列表,下载,上传,断开这最基础的命令,会这些,在使用ftp命令行就毫无压力啦!1. 连接ftp服务器格式:ftp a)在linux命令行下输入:b)服务器询问你用户名和密码,分别输入用户名和相应密码,待认证通过即可。2.列出文件列表以及切换目录这部分其实和linux并无区别,分别是ls,和cd列出目录列表切换当前目录3. 下载文件下载文件通常用get和mget这两条命令。a) get格式:get 将文件从远端主机中传送至本地主机中。如要获取远程服务器上/usr/your/1.htm,则

如何选择特征

特征工程是数据分析中最耗时间和精力的一部分工作,它不像算法和模型那样是确定的步骤,更多是工程上的经验和权衡。因此没有统一的方法。这里只是对一些常用的方法做一个总结。本文关注于特征选择部分。后面还有两篇会关注于特征表达和特征预处理。1. 特征的来源在做数据分析的时候,特征的来源一般有两块,一块是业务已经整理好各种特征数据,我们需要去找出适合我们问题需要的特征;另一块是我们从业务特征中自己去寻找高级数据特征。我们就针对这两部分来分别讨论。2.  选择合适的特征我们首先看当业务已经整理好各种特征数据时,我们如何去找出适合我们问题需要的特征,此时特征数可能成百上千,哪些才是我们需要的呢?第一

Go入门:五、goroutine和channel

这是我Go学习的第五篇笔记,学习的是go的语言的其他特性,这些特性是其他语言所不具备的。这次主要学习的是goroutine和channel。我的语言学习过程一般分为下面几个:1. 变量和数据类型2. 流程控制方法3. 函数声明和调用4. 面向对象5. 语言特性6. 常用标准库goroutine介绍和使用Go语言中,每个并发执行的单元称为goroutine(可类比线程)。当一个程序启动时候,main函数在一个main goroutine中运行。如果想要创建新的goroutine,使用go关键字!语法创建一个新的 goroutinechannel是goroutine的通信机制,比如创建一个能够接收

布隆过滤器(bloom filter)介绍以及php和redis实现布隆过滤器实现方法

引言在介绍布隆过滤器之前我们首先引入几个场景。场景一在一个高并发的计数系统中,如果一个key没有计数,此时我们应该返回0。但是访问的key不存在,相当于每次访问缓存都不起作用了。那么如何避免频繁访问数量为0的key而导致的缓存被击穿?有人说, 将这个key的值置为0存入缓存不就行了吗?这是确实是一种解决方案。当访问一个不存在的key的时候,设置一个带有过期时间的标志,然后放入缓存。不过这样做的缺点也很明显:浪费内存和无法抵御随机key攻击。场景二在一个黑名单系统中,我们需要设置很多黑名单内容。比如一个邮件系统,我们需要设置黑名单用户,当判断垃圾邮件的时候,要怎么去做。比如爬虫系统,我们要记录下

赞赏

微信赞赏支付宝赞赏

发表回复

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