原生js发送ajax请求
<script>
//原生js发送ajax请求
document.getElementById("ajax").onclick = function (){
//1.创建XMLHttpRequest
var xmlHttpRequest = new XMLHttpRequest();
//2.发送异步请求
xmlHttpRequest.open('GET','http://localhost:8080/ajax');
xmlHttpRequest.send();//发送请求
//3。获取服务器响应数据
xmlHttpRequest.onreadystatechange = function (){
if (xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200){
document.getElementById('table').innerHTML=xmlHttpRequest.responseText;
alert(xmlHttpRequest.responseText)
}
}
}
</script>
axios框架发送ajax请求
需引入js文件
<script src="js/axios.min.js"></script>
<script>
//1.get
axios({
method:"get",
url:"http://localhost:8080/ajax?username=zhangsan"
}).then(function (resp){
alert(resp.data)
})
//2.post
axios({
method:"post",
url:"http://localhost:8080/ajax",
data:"username=zhangsan"
}).then(function (resp){
alert(resp.data)
})
</script>