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>
用户名:<input type="text" id="uname">
<button οnclick="getMsg()">发送请求</button>
<div id="show"></div>
<script>
function getMsg(){
//1. 创建xhr
var xhr = createXhr();
console.log(xhr);
//2. 创建请求
var uname = $("uname").value;
xhr.open("GET","04-response.php?uname="+uname+"&upwd=123456",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
@$uname = $_REQUEST["uname"];
if($uname == null || $uname == ""){
die("uname required");
}
@$upwd = $_REQUEST["upwd"];
if($upwd == null || $upwd == ""){
die("upwd required");
}
echo $uname;
echo $upwd;
echo "我的第一个AJAX程序";
?>