原始交互:
-
实例化XMLHttpRequest
var xhr = new XMLHttpRequest();
2. 初始化请求行
xhr.open(method,url,async);
//async表示默认异步执行
3. 设置请求头
xhr.setRequestHeader(k,v)xhr.setRequestHeader("Content-type":"application/json") //()中存放键值对key-value 如果是get方式,无需设置Content-Type,因为Content-Type请求体中数据编码格式
- 设置请求体,并且发送请求
xhr.send(data)
如果是get方式,无需设置data - 监听请求状态的改变,来获取结果
xhr.onreadystatechange = function(){
if(xhr.readystate === 4){
if(xhr.status === 200){
// 获取结果
xhr.response // string -> json 、JSON.parse();
}
}
}
分开:
1.ajax
2.get请求
3.
(1)post提交json
(2)post提交querystring
- 设置请求体,并且发送请求