<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>this is ajax index</h1>
<div id="imgs">
假装有图
</div>
<input type="button" value="美图" onclick="sendXML()">
<script>
function sendXML() {
//alert("奥力给");
var xhr;
//原生Ajax 的四步骤
// 1. 创建XMLHTTpRequest对象
// 创建不同版本的Request对象
if (window.XMLHttpRequest){
//IE7+, Firefox,chrome,Opera,Safari 浏览器代码
xhr=new XMLHttpRequest();
}else {
//IE6 ,IE5 浏览器代码
xhr=new ActiveXObject("Microsoft.XMLHTTP")
}
// console.log(xhr.readyState)
// 2. 设置 onreadystatechange 的回调函数
//(这个函数是自己写的 可以拿到里面的内容)
xhr.onreadystatechange=function () {
if (xhr.readyState==4 && xhr.status==200){
document.getElementById("imgs").innerHTML=xhr.responseText;
/*
* innerHTML 将文本内容进行显示,带有标签的部分会自动解析
* innerText 直接将文本内容显示,不会解析各种html标签
* */
}
}
// 3. open() 打开链接
xhr.open("GET","pretty.html",false)
// 4. 发送请求
xhr.send();
alert(xhr);
}
</script>
<!--超链接的话 会跳转页面(地址会变) ,而这还是原来的页面(局部刷新)-->
</body>
</html>
原生Ajax 简易 四步
最新推荐文章于 2021-12-06 18:58:32 发布