XMLHttpRequest(简称xhr),是浏览器提供的javascript对象,通过它,可以请求服务器上的数据资源。后期便利的接口函数都是由xhr对象封装出来的。所以今天来尝试用xhr来实现请求
1.用xhr发起GET请求
1.创建xhr对象
var xhr = new XMLHttpRequest()
2.调用xhr.open()函数
//调用open函数,指定请求方式与URL地址
xhr.open('GET','http://www.baidu.com')
3.调用xhr.send()函数
//发起ajax请求:get里的send()函数里是不放数据的,如果想要有数据是需要放在地址的后面
xhr.send()
4.监听 xhr.onreadystatechange事件
xhr.onreadystatechange = function(){
if(xhr.readyState === 4 && xhr.status === 200){
//服务器返回的数据存储在xhr.responseText里
console.log(xhr.responseText)
}
2.用xhr发起POST请求
1.创建xhr函数
//和get请求一样
var xhr = new XMLHttpRequest()
2.调用xhr.open()函数
//调用open函数,指定请求方式与URL地址
xhr.open('POST','http://www.baidu.com')
3.设置 Content-Type属性
//写法是固定写法
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
4.调用xhr.send()函数
//将数据以查询字符串的方式提交给服务器
xhr.send('id = 1 & name = zs')
5.监听xhr.onreadystatechange事件
xhr.onreadystatechange = function(){
if(xhr.readyState === 4 && xhr.status === 200){
console.log(xhr.responseText)
}