1. 创建一个 XMLHttpRequest 对象
var request=new XMLHttpRequest();
2.打开连接,设置请求信息并发送数据
Get请求
request.open('get',URL="https://",true);
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
request.send();
Post请求
request.open('post',URL="https://",true);
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
request.send('hellow=','world');
后端接收到的post 表单信息
{'hellow':'world'}
其中,open里的true 表示异步,false 表示同步
3.最重要的一步,设定接收请求函数
function change(){
if(request.readyState==4 && request.status==200)//判断后端是否成功接收信息
{
alert(request.responseText);//弹出后端返回的信息
}
}
request.onreadystatechange=change;//设置接收函数
一定注意,不要直接用 if 判断 后端是否成功接收信息!要设定函数,否则收不到后端返回的信息(亲自踩过坑)
本文若对你有帮助,请留下一个赞激励我…… | |
---|---|
如有不足之处,欢迎评论区指正…… |