自封装的Ajax.js文件
function obj2str(data) {
data.t=new Date().getTime();
var res=[];
for(var key in data){
res.push(encodeURIComponent(key)+"="+encodeURIComponent(data[key]));
}
return res.join("&");
}
function ajax(option) {
var str=obj2str(option.data);
var xmlhttp,timer;
if(window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}else{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if(option.type==="GET"){
xmlhttp.open(option.type,option.url+"?"+str,true);
xmlhttp.send();
}else{
xmlhttp.open(option.type,option.url,true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(str);
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === 4) {
clearInterval(timer);
if (xmlhttp.status >= 200 && xmlhttp.status < 300 || xmlhttp.status === 304) {
option.success(xmlhttp);
} else {
option.error(xmlhttp);
}
}
}
if(option.timeout){
timer=setInterval(function () {
console.log("中断请求");
xmlhttp.abort();
clearInterval(option.timer);
},option.timeout);
}
}
调用Ajax方法的index.html文件
在<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="111.js"></script>
<script>
window.onload=function () {
var oBtn=document.querySelector("button");
oBtn.onclick=function () {
ajax({ type:"POST/GET",
url:"https://www.baidu.com或php等后端文件",
data:{"userName":"你的名字","password":"你的密码"},
timeout: 3000,
sunccess:function (xhr) {
alert(xhr.responseText);
},
error: function (xhr) {
alert("请求失败");
})
}
}
}
</script>
</head>
<body>
<button> 发送请求</button>
</body>
</html>