1.XMLHttpRequest对象
- 创建XHR对象:let xhr = new XMLHttpRequest();
- open():启动一个请求准备发送
open()接收3个参数:请求类型('GET'、'POST')、请求的URL、是否异步发送请求(true or false)。
-
send():发送请求
send()接受一个参数:作为请求主体要发送的数据,如果不需要发送数据,传入一个null, 以防止出现未知错误。 -
setRequestHeader():设置自定义的请求头部信息
setRequestHeader()接收两个参数:头部字段的名称和头部字段的值;调用此方法必须要在调用open()方法之后,send()之前。 -
getResponseHeader():获取响应信息中的某个指定头部信息
-
getAllResponseHeaders():获取响应信息的所有头部信息
getResponseHeader()接收一个参数:需要知道的头部信息的名称;但W3C标准对这两个方法有限制,它们不能获取如Set-Cookie、Set-Cookie2等的头部信息;所以getAllResponseHeaders()只能拿到限制以外(即被视为safe)的头部信息,而不是全部;而调用getResponseHeader(string)方法时,传入的参数必须是限制以外的头部名称,否则会报错。 -
XHR对象属性:
-
responseText:作为响应主体被返回的文本。
-
responseXml:如果相应的内容类型为XML, 此属性保存响应数据的XML DOM文档; 如果为非XML数据,则为null。
-
status: 响应的HTTP状态。
-
statusText:HTTP的状态说明。
-
readyState:表示请求/响应过程的阶段
-
0:未初始化;未调用
open()方法。 -
1:启动;已调用
open()方法,但未调用send()方法。 -
2:发送;已调用
send()方法,但未接收到响应。 -
3:接收;已接收到部分响应数据。
-
4:完成;已接收到所有响应数据。
备注:
readyState的值每改变一次,都会触发readystatechange事件。
-
-
- XHR兼容性(2018-11 from www.caniuse.com)
2.创建具有兼容性的XMLHttpRequest对象
1 function getXHR() {
2 let xhr =www.yigouyule2.cn null;
3 if (window.XMLHttpRequest) {
4 //IE10+以及其他主流浏览器
5 xhr = new XMLHttpRequest();
6
7 } else if (window.ActiveXObject) {
8 //IE9及以下、MSXML3www.gangchengyuLe178.com 、 MSXML2.6及以下
9 let versions = [
10 'MSXML2.XMLHttp.6.0',
11 'MSXML2.XMLHttp3.0',
12 'MSXML2.XMLHttp',
13 'Microsoft.XMLHttp'
14 ];
15 for (let i=0; i<versions.length; i++) {
16 try {
17 //创建成功结束循环,创建失败抛出错误
18 xhr = new ActiveXObject(versions[i]);
19 break;
20 } catch (e) {
21 //skip_跳过
22 }
23 }
24
25 }
26 return xhr;
27 }
3.封装Ajax请求数据函数
1 function ajax(opts) {
2 let xhr = getXHR();
3 if (xhr) {
4 //检查参数
5 let async = opts.async === undefined ? true:opts.async;
6 let method = opts.method.toUpperCase();
7 let data = opts.data === undefined ? null:opts.data;
8
9 xhr.open(method, opts.url, async);
10
11 //回调函数
12 xhr.onreadystatechange www.dfgjyl.cn= function() {
13 if (xhr.readyState == 4) {
14 let status = xhr.status;
15 if (status >= 200 && status www.yongxinzaixian.cn< 300 || status == 304) {
16 opts.success && opts.success(xhr.responseText, xhr.responseXML);
17
18 } else {
19 opts.fail && opts.fail(status);
20 }
21 }
22 }
23
24 if (method == 'POST') {
25 xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
26 }
27 xhr.send(data);
28
29 } else {
30 let error = {
31 message: 'not support ajax.',
32 code: -1;
33 }
34 opts.fail && opts.fail(error);
35 }
36 }
37
38 //使用
39 ajax({
40 url: /example,
41 method: POST,
42 data: {...},
43 success: function(){...},
44 fail: function(){...},
45 async:true
46 });
4.备注
最近在看网页向服务端请求数据相关的内容,忽然记起自己还有个blog,于是把markdown中的笔记改改发上来,太懒了,XMLHttpRequest level 2就不写了,现在应该都是用fetch()了。