Ajax封装代码部分:
function obj2str(obj){
// 防止URL不变导致IE调用缓存
obj.t = new Date().getTime();
let res = [];
for (let key in obj){
// URL中不能有中文,需要转码,即调用encodeURLComponent()
res.push(encodeURIComponent(key)+"="+encodeURIComponent(obj[key]));
}
return res.join('&');
}
function ajax(url,obj,timeout,success,error){
let str = obj2str(obj);
let xhr,timer;
if (XMLHttpRequest)
{
xhr = new XMLHttpRequest();
}
else
{
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.open("GET",url+"?"+str,true);
xhr.send();
xhr.onreadystatechange = function (){
if (xhr.readyState === 4){
clearInterval(timer);
if (xhr.status >= 200 && xhr.status < 300 || xhr.status === 340){
success(xhr);
} else{
error(xhr);
}
}
}
// 判断外界是否传入超时时间
if (timeout){
timer = setInterval(function (){
console.log("中断请求")
xhr.abort();
clearInterval(timer);
},timeout)
}
}
php处理部分:
<?php
//sleep(5);
echo "ajax get pages";
echo $_GET["userName"];
echo "<br>";
echo $_GET["userPwd"];
html中调用:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<button>click</button>
<script src="3.Ajax-Get-package.js"></script>
<script>
window.onload = function (){
let oBtn = document.querySelector("button");
oBtn.onclick = function (){
ajax(
"3.Ajax-Get-package.php",{
"userName":"eyes++",
"userPwd":"123456"
},
3000,
function (xhr){
alert(xhr.responseText);
},
function (xhr){
alert("请求失败!");
});
}
}
</script>
</body>
</html>
更多相关内容大家可以前往我的个人博客浏览:eyes++的个人空间