1. 创建文件名为“someResource”的文件(文件无后缀),文件类型:文件,在文件夹中如下图:
"someResource"文件代码:
<b>This is the content of resource <tt>someResource</tt></b>
2. HTML代码:
<!DOCTYPE html>
<html>
<head>
<title>使用原生XHR来获取并包括HTML片段</title>
<meta charset="utf-8">
<script type="text/javascript" src="js/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
window.onload = function() {
//创建XHR
var xhr;
//测试ActiveX是否存在
if (window.ActiveXObject) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
//测试XHR是否已经被定义
else if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
//如果不支持Ajax则抛出错误
else {
throw new Error("Ajax is not supported by this browser");
}
xhr.onreadystatechange = function() {
//就绪处理器,忽略除DONE状态之外的所有状态
if (this.readyState == 4) {
//根据响应状态进行代码分支
if (this.status >= 200 && this.status < 300) {
//成功时执行
document.getElementById(‘someContainer‘)
.innerHTML = this.responseText;
}
}
};
xhr.open(‘GET‘,‘someResource‘);
xhr.send(‘‘);
};
</script>
</head>
<body>
<div id="someContainer"></div>
</body>
</html>