Ajax发送请求和接受结果要使用一个对象(XMLHttpRequest)
- 创建xhr对象
let xhr = null
if(){
xhr=new XMLHttpRequest();
}else {
xhr=new ActiveXObject('Msxml2.XMLHTTP')
}
- 发送请求使用到两个方法
准备请求:open([get/post],[url],[true/false]) 发送请求:send([val]) get请求值为null或不写,post请求[val]为发送到后端的数据
- 接受数据(xhr的核心事件onreadystatechange)
xhr.onreadystatechange=function (){
if(xhr.readyState==4){
xhr.responseText
}
}
- get请求
open(‘get’,’/api’)
send()
get请求可以在url地址已key和val形式携带少量数据(/api?name=yy&age=18)
- post请求
- FormData表单对象
Content-Type:application/json和application/x-www-form-urlencoded区别
application/json和application/x-www-form-urlencoded都是表单数据发送时的编码类型。
默认地,表单数据会编码为 “application/x-www-form-urlencoded”。就是说,在发送到服务器之前,所有字符都会进行编码。
- application/x-www-form-urlencoded编码类型的发送和接收
以这种key1=value1&key2=value2的方式发送到服务器。如果用Jquery,它内部已经进行了处理,如果自己写原生的Ajax请求,就需要自己对数据进行序列化。
- application/json的发送和接收
序列化后的 JSON 字符串