Ajax异步请求
一、Ajax异步请求介绍
-
同步请求。也就是刷新浏览器的请求。一个结束后,另一个才能发起
-
异步请求,也叫Ajax请求。不刷新浏览器,体验更好。数据是异步获取的,可以同时发起多个请求
-
回调。Ajax请求一定会有回调,一般用于处理服务器端返回的数据
-
打开静态页面:http://localhost:8080/03jquery/08-ajax.html
二、代码实战
自己编写的Ajax请求
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript" src="./res/jquery-1.11.3.min.js"></script>
</head>
<body>
<div id="myDiv">eeee</div>
<!-- 点击事件 -->
<button id="myBtn" onclick="doClick()">点击</button>
<script type="text/javascript">
function doClick(){
ajaxRequest();
}
function ajaxRequest(){
//实例化请求对象
let xmlHttpRequest;
if(window.ActiveXObject){ //IE浏览器的创建方式
xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}else if(window.XMLHttpRequest){
xmlHttpRequest = new XMLHttpRequest();
}
// 响应http请求
xmlHttpRequest.onreadystatechange=function(){
// 判断异步调用是否成功
if(xmlHttpRequest.readyState == 4){
if(xmlHttpRequest.status == 200) {
//请求成功
// alert(xmlHttpRequest.responseText)
let txt = xmlHttpRequest.responseText
$('#myDiv').html(txt)
} else {
alert("失败:HTTP状态码为:"+xmlHttpRequest.status);
}
}
}
//发起请求
xmlHttpRequest.open("GET","http://localhost:8080/hiajax",true);
xmlHttpRequest.send(null); // 发送请求
}
</script>
</body>
</html>