一、封装myAJAX函数
function obj2str(obj){
var res=[];
for(var key in obj){
res.push(key+"="+obj[key]);
}
return res.join("&");
//res.join("&")让数组的元素转换成一个字符串,用&分隔开
//split是将字符串分割成数组
}
function ajax(obj) {
var xmlhttp = new XMLHttpRequest();
var str=obj2str(obj.data);
xmlhttp.open(obj.type, obj.url + "?" + str,true);
//用GET获取前端的数据,获取结果就是url?key=result&key2=result2
//比如 test04.php?username=jianjian&userpsw=123456
//url+"?"+str就是服务器获取GET得到的前端数据的格式,会在url后显示
//所以这句话就是表示后端所接收的信息,在php中也可以处理这些数据,
//因为GET得到的数据会在url后显示,所以这些数据表示已经被php所获得
xmlhttp.send();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === 4) {
clearInterval(timer);
console.log(xmlhttp.readyState);
if (xmlhttp.status >= 200 && xmlhttp.status < 300 || xmlhttp.status === 304) {
console.log(xmlhttp.status);
obj.success(xmlhttp);
//引用对象里的函数,要加括号和括号里的参数,
//该函数的名字就是函数在对象中的名字
} else {
obj.error(xmlhttp);
}
}
}
if(obj.timeout){
timer=setInterval(function(){
console.log("中断请求");
xmlhttp.abort();
clearInterval(timer);
},obj.timeout);
}
}
二、HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="myAJAX03.js"></script>
<script>
window.onload=function(){
var btn=document.querySelector("button");
btn.onclick=function(){
ajax({
type:"GET",
url:"05-test.php",
data:{
username:"jianjian",
userpsw:"123456"
},
timeout:"3000",
success:function(xhr){
alert(xhr.responseText);
},
error:function(){
alert("请求失败")
}
})
}
}
</script>
</head>
<body>
<button>发送请求</button>
</body>
</html>
三、PHP
<?php
echo $_GET["username"];
//url+“?”+str
//str就是GET获取到的数据
echo $_GET["userpsw"];
?>
四、结果