封装ajax_回调函数.html 页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
function $ajax({method = "get",url,data,sucess,error}){
var xhr = null;
try{
xhr = new XMLHttpRequest();
}catch(error){
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
if(data){
data = querystring(data);
}
if(method == "get" && data){
url += "?" + data;
}
xhr.open(method,url,true);
if(method == "get"){
xhr.send();
}else{
xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");
xhr.send(data);
}
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
if(xhr.status == 200){
if(sucess){
sucess(xhr.responseText);
}
}else{
if(error){
error("Error:" + xhr.status);
}
}
}
}
}
function querystring(obj){
var str ="";
for (var attr in obj) {
str += attr + "=" + obj[attr] +"&";
}
return str.substring(0,str.length - 1)
}
window.onload = function(){
var oGetBtn = document.getElementById("getBtn");
var oPostBtn = document.getElementById("postBtn")
;
oGetBtn.onclick = function(){
$ajax({
url: "1.get.php",
data: {
username:"xxx",
age: "18",
password: "123abc"
},
sucess: function(result){
alert("GET请求下载到的数据:" + result);
},
error: function(msg){
alert(msg);
}
})
}
oPostBtn.onclick = function(){
$ajax({
method: "post",
url: "1.post.php",
data: {
username:"xxx",
age: "18",
password: "123abc"
},
sucess: function(result){
alert("POST请求下载到的数据:" + result);
},
error: function(msg){
alert(msg);
}
})
}
}
</script>
</head>
<body>
<button id="getBtn">GET请求</button>
<button id="postBtn">POST请求</button>
</body>
</html>
1.get.php 页面
<?php
header('content-type:text/html;charset="utf-8"');
$username = $_GET['username'];
$age = $_GET['age'];
$password = $_GET["password"];
echo "你的名字:{$username},年龄:{$age},密码:{$password}";
?>

1.post.php 页面
<?php
header('content-type:text/html;charset="utf-8"');
$username = $_POST['username'];
$age = $_POST['age'];
$password = $_POST["password"];
echo "你的名字:{$username},年龄:{$age}, 密码:{$password}";
