原生js发送ajax请求

1.接口getdata.php

header("Content-type:text/html;charset=utf-8");
//设置响应头,禁止缓存,告诉浏览器不要读取缓存文件
header("Cache-Control:no-cache,must-revalidate");
echo  "<div>我是<span style='color:red'>凤姐约吗,哪里约,与".$_GET['name']."约12345689112233445566</span></div>";

2.页面fahuo.html

<button type="button" onClick='fahuo()'>发货</button>
<div id='result'></div>
function fahuo(){
   //1.创建ajax对象
   var xhr = new XMLHttpRequest();
   //2.监听ajax状态的改变的事件,在此事件处理中判断状态等于4,接收数据,处理业务逻辑
    xhr.onreadystatechange=function(){
    if(xhr.readyState == 4){
        //获取服务器响应的数据
        var response = xhr.responseText;//response是接口返回来的数据
        //把返回来数据写在id为result的div中
        document.getElementById('result').innerHTML =  response;
    }
}
   //3.建立http连接
   xhr.open("get","getdata.php?name=lisi&age=44",true); //true异步  false同步
   //4.发送ajax请求
   xhr.send(null);
  }
原文地址:https://www.cnblogs.com/xiaobiaomei/p/7826199.html