一、名称
异步的javascript and xml
二、原理
1、通过 XMLHttpRequest 与服务器交换数据
2、服务数据通过json 或者 xml格式返回
3、浏览器端通过js+ccs渲染展示数据
三、get请求
<button type="button" id=btn>发送</button>
<p id="zoon"></p>
<script type="text/javascript">
btn.onclick=function(){
//创建xhr
var xhr=new XMLHttpRequest();
//打开链接
xhr.open("GET",'zen.txt',false);
//监听事件 readyState状态码 statu由服务器返回的状态行的值。
xhr.onreadystatechange=function(){
if(xhr.status==200&&xhr.readyState==4){
zoon.innerHTML=xhr.responseText;
}
}
//发送
xhr.send();
}
</script>
四、post请求
input type="text" id="in1" value="" placeholder="请输入用户名"/>
<input type="text" id="in2" value="" placeholder="请输入年龄"/>
<button type="button" id="btn">发送</button>
<p id="zoon"></p>
<script type="text/javascript">
btn.onclick=function(){
//创建xhr链接
var xhr=new XMLHttpRequest();
var name=document.getElementById("in1").value;
console.log(name)
var age=document.getElementById('in2').value;
var zoon=document.getElementById('zoon');
//打开
xhr.open('POST','http://localhost/echo.php',false);
//监听事件
xhr.onreadystatechange=function(){
if(xhr.status==200&&xhr.readyState==4){
zoon.innerHTML=xhr.responseText;
}
}
// 设置请求头格式
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
//发送
xhr.send(`name=${name}&age=${age}`);
}
</script>