<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Ajax基本封装</title>
</head>
<script>
function ajax(method,url,params,done) {
var xhr = new XMLHttpRequest();
var data= null;
method = method.toUpperCase();//处理用户大小写规范
//将object类型的参数转换为key=value&key2-value2
if (typeof params ==="object"){
var tempArr=[];
for(var key in params){
var value = params[key]
tempArr.push(key + '='+ value)
}
//tempArr =>['key1=value','key2=value2'
params = tempArr.join('&')
}
if (method==='GET'){
url +='?' + params
}
xhr.open(method,url);
if (method==='POST'){
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencode');
data=params;
}
xhr.send(data);
xhr.onreadystatechange=function () {
if (this.readyState!==4) return;
done(this.responseText)
}
}
ajax('GET','time.php',{id:1},function (res) {
console.log(res);
//拿到数据要做的事
});
ajax('POST','time.php',{key1:'value1',key2:'value2'},function (res) {
console.log(res)
})
</script>
<body>
</body>
</html>
原生Ajax简单封装
最新推荐文章于 2023-04-05 17:32:02 发布