基于XMLHttpRequest对象
创建两个页面,a,b.
a页面完整代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>a</title>
<style>
body {
font-size: 13px;
}
.divFrame {
width: 260px;
border: 1px solid #666;
}
.divFrame .divTitle {
padding: 5px;
background-color: #eee;
}
.divFrame .divContent {
padding: 8px;
}
.divFrame .divContent .clsShow {
font-size: 14px;
}
.btn {
padding: 2px;
width: 100px;
color: #fff;
background: #28e;
border: none;
}
</style>
</head>
<body>
<div class="divFrame">
<div class="divTitle">
<input id="Button1" type="button" onclick="GetSendData()" class="btn" value="获取数据" />
</div>
<div class="divContent">
<div id="divTip"></div>
</div>
</div>
<script>
var objXmlHttp = null; //声明一个空的XMLHTTP变量
function CreateXMLHTTP() {
//根据浏览器的不同,返回该变量的实体对象
if (window.ActiveXObject) {
objXmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} else {
if (window.XMLHttpRequest) {
objXmlHttp = new XMLHttpRequest();
} else {
alert("初始化XMLHTTP错误!")
}
}
}
function GetSendData() {
document.getElementById('divTip').innerHTML =
"<img alt=''' title='正在加载中...' src='././img/load.png'>" //初始化内容
//设置发送地址变量并赋值
var strSendUrl = "b.html?data=" + Date();
CreateXMLHTTP(); //实例化XMLHttpRequest对象
//open方法初始化XMLHttpRequest
objXmlHttp.open("GET", strSendUrl, true);
objXmlHttp.onreadystatechange = function() { //回调事件函数
if (objXmlHttp.readyState == 4) { //如果请求完成加载
if (objXmlHttp.status == 200) { // 如果响应已成功
document.getElementById("divTip").innerHTML = objXmlHttp.responseText; //显示响应的数据 }
}
}
}
objXmlHttp.send(null); //send发送设置的请求
}
</script>
</body>
</html>
b页面代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>b</title>
<style>
.clsShow {
font-size: 14px;
}
</style>
</head>
<body>
<div class="clsShow">
name: jin <br/> age: 29 <br/> e-mail: jin@163.com
</div>
</body>
</html>
jquery load方法加载数据:
$(function() {
$("#Button1").click(function() {
$("#divTip").load("b.html")
})
})
最后一步,需要放在服务器上运行,否则会报跨域问题的错误
直接打开html操作后的结果,显示如下图错误:
我启动tomcat运行的结果: