AJAX在网站服务中使用到频率很高,也需要考虑各个浏览器版本的兼容性,本示例中详细介绍简单快捷的处理兼容性问题。
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>AJAX</title>
<style>
.myBtn{
background:#3498db;
color:#fff;
font-size:14px;
text-align:center;
width:100px;
height:36px;
line-height:34px;
border:none 0;
cursor:pointer;
}
</style>
<script>
window.onload = function() {
var oBtn = document.getElementById('btn');
oBtn.onclick = function() {
/*
1.创建一个ajax对象
ie6以下new ActiveXObject('Microsoft.XMLHTTP')
*/
var xhr = null;
//第一种处理兼容方式
/*if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest(); //Firefox(或其他非IE)
} else {
xhr = new ActiveXObject('Microsoft.XMLHTTP'); //IE浏览器
}*/
//第二种处理兼容方式
try {
xhr = new XMLHttpRequest();
} catch (e) {
xhr = new ActiveXObject('Microsoft.XMLHTTP');
}
/*
open方法
参数
1.打开方式
2.地址
3.是否异步
异步:非阻塞 前面的代码不会影响后面代码的执行
同步:阻塞 前面的代码会影响后面代码的执行
*/
xhr.open('get','links/1.txt',true);
//提交 发送请求
xhr.send();
//等待服务器返回内容
xhr.onreadystatechange = function() {
if ( xhr.readyState == 4 ) {
alert( xhr.responseText );
}
}
}
}
</script>
</head>
<body>
<input type="button" value="按钮" id="btn" class="myBtn" />
</body>
</html>
通过创建对象,使用try catch语句:try…catch 可以测试代码中的错误。try 部分包含需要运行的代码,而 catch 部分包含错误发生时运行的代码。通过open方法来发送请求的地址等待返回结果。