common.js
//common.js
function $(id){
return document.getElementById(id);
}
var xhr;
function createXhr() {
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest();
return xhr;
}else{
xhr = new ActiveXObject("Microsoft XMLHttp");// Microsoft XMLHttp大小写随意
return xhr;
}
}
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="common.js"></script>
</head>
<body>
<button οnclick="getMsg()">发送请求</button>
<div id="show"></div>
<script>
function getMsg(){
//1. 创建xhr
var xhr = createXhr();
console.log(xhr);
//2. 创建请求
xhr.open("GET","04-response.php",true);
//3. 设置回调函数—onreadystatechange
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200){ //status
//接收响应数据
console.log("1111");
var resText = xhr.responseText;
$("show").innerHTML = resText;
console.log(resText);
}
}
//4. 发送请求
xhr.send();
}
</script>
</body>
</html>
04-response.php
<?php
echo "我的第一个AJAX程序";
?>