<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<meta http-equiv="X-UA-Compatible" content="ie=edge"/>
<title>Document</title>
<script>
function $ajax({method = "get",url,data,success,error}){
var xhr = null;
try{
xhr = new XMLHttpRequest();alert("创建");
}catch(error){
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
function querystring(obj){
var str='';
for(var t in obj)
{str += t + "=" + obj[t] + "&";} alert('成功转化');
return str.substring(0,str.length-1);
}//将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(success)
alert("运行成功");
success(xhr.responseText);
}else{
if(error)
error("Error:" + xhr.status);
}
}
}
}
/*window.onload = function(){
var oBtn = document.getElementById("btn1");
oBtn.onclick = function(){
//1、创建ajax对象
var xhr = null;
try{
xhr = new XMLHttpRequest();//xhr =new XMLHttpRequest();
}catch(error){
xhr = new ActiveXObject("Microsoft.XMLHTTP");//xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
//2、调用open
xhr.open("get", "1.get.php?username=yyy&age=19&password=123abc", true);
xhr.open("post","1.post.php",true);
//3、调用send
//xhr.setRequestHerder("content-type","application/x-www-form-urlencoded");
xhr.send();
//xhr.send("username=yyds&age=19&password=123abc");
//4、等待数据响应
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
//判断本次下载的状态码都是多少
if(xhr.status == 200){
alert(xhr.responseText);
}else{
alert("Error:" + xhr.status);
}
}
}
}
}*/
</script>
</head>
<body>
<button id = 'btn1'>GET请求</button>
<button id = 'btn2'>POST请求</button>
<script>window.οnlοad=function(){
var btn1=document.querySelector('#btn1');
var btn2=document.querySelector('#btn2');
btn1.οnclick=function(){alert("1");
$ajax({
url:"1.get.php",
data:{username:11,
age:18,
password:"123abc",},
success:function(result){
alert("回调成功" + ' \n'+ result);
},
error:function(msg){
alert("失败" + msg);
},
})
}
btn2.οnclick=function(){
$ajax({
method:"post",
url:"1.post.php",
data:{username:11,
age:18,
password:"123abc"},
success:function(result){
alert("回调成功" + ' \n'+ result);
},
error:function(msg){
alert("失败" + msg);
},
})
}}
</script>
</body>
</html>