Ajax

本文详细介绍了如何使用XMLHttpRequest(XHR)进行HTTP请求,包括创建XHR对象、发送GET和POST请求的方法,以及如何处理响应。此外,还介绍了XHR2级新增的功能,如FormData对象和超时设置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

《JavaScript高级程序设计》21.1

1、创建XHR对象

function creatXHR(){
    if (window.XMLHttpRequest){
        // for IE7+, Firefox, Chrome, Opera, Safari
        return new XMLHttpRequest();
    }else{
        // for IE6, IE5
        return new ActiveXObject("Microsoft.XMLHTTP");
    }
}

var xhr = createXHR();

2、XHR的用法

要是用XHR对象,要调用的第一个方法是open()方法。它接收三个参数:发从请求的类型(get/post),请求的url和表示是否异步发送请求的布尔值。
xhr.open('get','example.php',false);// false表示同步请求
然后调用send()方法发送请求。
xhr.send(null);
send()方法接收一个参数,即要作为请求主体发送的参数。如果没有数据,必须传入参数null,因为这个参数对于有些浏览器来说是必须的。

由于这次请求是同步的,JS代码会等到服务器响应后继续执行。接收到响应后,xhr对象的属性会被自动填充。属性如下:

responseText作为响应主体的文本
responseXML响应内容为text/xml或者application/xml时,这个属性中将包含着响应数据的XML DOM文档。
status响应的HTTP状态
statusTextHTTP状态的说明


接收到响应后,第一步检查status属性,当200<=status<300或status为304时,说明这个请求是成功的。

xhr.open('get','example.php',false);
xhr.send(null);
if(xhr.status>=200 && xhr.status<300 ||xhr.status==304){
    console.log(xhr.responseText);
}else{
    console.log('request was unsuccessful:'+xhr.status);
}


无论响应内容类型是什么,响应的主体内容都会保存到responseText中。

当进行异步请求时,可以检测XHR对象的readyState属性。该属性表示请求/响应过程的当前活动阶段:

readyState阶段说明
0初始化尚未调用open()方法
1启动已经调用open()方法,尚未调用send()方法
2发送已经调用send()方法,尚未收到响应
3接收已经接收到部分响应数据
4完成已经接收全部响应数据,且已经可以在客户端使用了


当readyState属性发生变化时,会触发一次readystatechange事件。事件处理程序应该在open()方法调用前指定。

var xhr = createXHR();
xhr.onreadystatechange = function(){
    if(xhr.status>=200 && xhr.status<300 || xhr.status==304){
        console.log(xhr.responseText);
    }else{
        console.log('request was unsuccessful:'+xhr.status);
    }
};
xhr.open('get','exmple.php',true);
xhr.send(null);

另外,在接收到响应之前可以调用xhr.abort()方法取消异步请求。

3.HTTP头部信息

使用setRequesHeader()方法可以设置自定义的请求头部信息,该1方法接收两个参数:key和value。
此方法必须在open()方法之后send()方法之前调用。

var xhr = createXHR();
xhr.onreadystatechange = function(){
    if(xhr.status>=200 && xhr.status<300 || xhr.status==304){
        console.log(xhr.responseText);
    }else{
        console.log('request was unsuccessful:'+xhr.status);
    }
};
xhr.open('get','exmple.php',true);
xhr.setRequestHeader('MyHeader','MyValue');
xhr.send(null);

接收到响应后,可以调用getResponseHeader()方法并传去头部字段名称获得相应的响应头部信息。
另外,getAllResponseHeaders() 方法可以获得一个包含所有头部信息的字符串。

4.GET请求

使用GET请求经常会发生一个错误,就是查询字符串的格式有问题。查询字符串中每个参数的key和value都必须使用encodeURIComponent()方法进行编码。so,我们可以写一个函数专门用来给URL添加查询字符串参数:

function addURLParam(url,name,value){
    url += (url.indexOf('?') == -1 ? '?' : '&');
    url += encodeURIComponent(name) + '=' +encodeURIComponent(value);
    return url;
}
var url = 'example.php';
url = addURLParam(url,'name','wss');

xhr.open('get',url,true);

5.POST请求

使用POST请求分两步,第一步当然是open()方法。

xhr.open('post','example.php',true);

第二步是向send()方法中传入数据。
由于XHR最初设计主要是为了处理XML,因此可以传入XML DOM文档,传入的文档经过序列化之后将作为请求主题提交数据。当然,也可以传入字符串。

默认情况下,服务器对POST请求和Web表单的请求并不会一视同仁。我们可以使用XHR来模仿表单提交:
首先,设计头部信息Content-Type为application/x-www-form-urlencoded(表单提交时的内容类型)。
然后,将表单中的数据序列化(使用serialize()函数)。

function submitData(){
    var xhr = createXHR();
    xhr.onreadystatechange = function(){
        if(xhr.readyState ==4){
            if(xhr.status >= 200 && xhr.status < 300 || xhr.status == 304){
                console.log(xhr.responseText);
            }else{
                console.log('request was unsuccessful:'+xhr.status);
            }
        }
    };
    xhr.open('post','postexample.php',true);
    // 设置头部信息
    xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');
    var form = document.getElementById('user-info');
    // 序列化表单
    xhr.send(serialize(form));
}

如果发送数量相同的数据,GET请求的速度最多可以达到POST请求的两倍,GET请求的性能更好。

6.XMLHttpRequset 2级

XHR的新功能

1.FormData

直接看例子:

    var xhr = createXHR();
    xhr.onreadystatechange = function(){
        if(xhr.readyState ==4){
            if(xhr.status >= 200 && xhr.status < 300 || xhr.status == 304){
                console.log(xhr.responseText);
            }else{
                console.log('request was unsuccessful:'+xhr.status);
            }
        }
    };
    xhr.open('get','postexample.php',true);
    var form = document.getElementById('user-info');
    xhr.send(new FormData(form));
}

相比上面“POST请求中的Form”,省去了设置头部信息的操作。FormData还有另一种用法:

var data = new FormData();
data.append("name","WSS");

传入键值对的数据。

2.超市设置

直接看例子:

    var xhr = createXHR();
    xhr.onreadystatechange = function(){
        if(xhr.readyState ==4){
            try{
                if(xhr.status >= 200 && xhr.status < 300 || xhr.status == 304){
                    console.log(xhr.responseText);
                }else{
                    console.log('request was unsuccessful:'+xhr.status);
                }
            }catch(ex){
                // 假设由ontimeout事件处理程序处理
            }
        }
    };
    xhr.open('get','timeout.php',true);
    xhr.timeout = 1000;
    xhr.ontimeout = function(){
        alert('Request did not return in a second.');
    };
    xhr.send(null);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值