HTTP请求3个组成部分与XMLHttpRequest方法的对应关系
1、请求行
2、请求头
get 请求可以不设置
3、请求主体
get请求
//创建一个异步
var xhr = new XMLHttpRequest();
//设置请求行 open (请求方法, 请求url)
//get请求如果有参数就需要在url后面拼接参数
//post请求在请求体中传递
xhr.open('get', 'index.php?'+name);
//设置请求头 setRequestHeader('key', 'value')
//get方式不需要设置请求头
//post需要设置 Content-Type: application/x-www-form-urlencoded
//设置 请求体: 发送请求 send(参数: key=value&key=value)
//如果有参数,post应该在这个位置来传递参数
//对于get请求不需要再这个位置来传递参数
xhr.send(null);
//响应报文:
//报文行: 响应状态码 响应状态信息 200 ok
//报文头: 服务器返回给客户端的一些额外的信息
//报文体: 服务器返回给客户端的数据 responseText: 普通字符串 responseXML: 符合xml格式的字符串
//xhr.status可以获取当前服务器的响应状态
//一个真正的响应应该两个方面: 1.服务器成功响应 2.数据已经回到客户端并且可以使用了
//监听异步对象响应状态 readystate
xhr.onreadystatechange = funciton () {
if(xhr.readyState == 4 && xhr.status == 200) {
var result = document.querySelect('.result');
result.innerHTML = xhr.responseText;
}
}
post请求
document.querySelect("#username").onblur = funciton () {
//1.获取用户数据
var name = this.value;
//2.让异步对象发送post请求
//2.1创建异步对象
var xhr = new XMLHttpRequest();
//2.2设置请求行 open(请求方式, 请求url)
//1.get 需要在url后面拼接参数
//2.post 不需要拼接参数
xhr.open("post","001.php?"+name)
//2.3设置请求头: setRequestHeader()
//1.get不需要设置
//2.posr需要设置 Content-Type: application/x-www-form-urlencoded
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
//2.4设置请求体 send()
//1.get的参数在url中拼接了,所以不需要在这个中设置
//2.post的参数在这个函数张设置
xhr.send('name=itcast&age=10');
//3.让异步对象接收服务器的响应数据
//一个真正的响应应该两个方面: 1.服务器成功响应 2.数据已经回到客户端并且可以使用了
xhr.onreadystatechange = function () {
if(xhr.status == 4 && xhr.readyState == 4) {}
document.querySelect(".showmsg").innerHTML = xhr.responseText;
}
}
GET和POST请求方式的差异
1、GET没有请求主体,使用 xhr.send(null)
2、GET可以通过在请求URL上添加请求参数
3、POST可以通过xhr.send(‘name=itcast&age=10’)
4、POST需要设置
Content-type:application/x-www-form-urlencoded
5、GET大小限制约4K,POST则没有限制
6、POST更安全