您的位置:首页 > Web前端 > JavaScript

原生JS封装Ajax

2017-08-16 09:49 316 查看
这里写一个原生JS封装ajax的demo。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>封装ajax</title>
</head>
<body>
<script>

let $={
ajax:function(opt){
if(!opt.url) return;
let url=opt.url,
type=opt.type||true,
data="",
xhr=null;
//兼容IE及非IE浏览器
try{
xhr=new XMLHttpRequest();
}catch(e){
xhr=new ActiveXObject("Microsoft.XMLHTTP");
}
if(typeof opt.data=="boject"){
for(let key in opt.data){
data+=key+"="+opt.data[key]+"&";
}
data=data.substr(0,data.length-1);
}
// 判断请求方式,注意post要比get多加一句setRequestHeader
if(type=="get"){
xhr.open("get",url+"?"+data,true);
xhr.send();
}else{
x
b672
hr.open("post",url,true);
xhr.setRequestHeader("content-type","application/x-www-form-urlencoded");
xhr.send(data);
}
// 依据状态码判断请求是否成功
xhr.onreadystatechange=function(){
if(this.readyState==4){
if(this.status==200){
let r=this.responseText;
console.log(r);
}else {
console.log('失败'+this.status);
}
}
}
}
}
$.ajax({
url:"post.txt",
data:{"name":"bobo"},
type:"post"
})
</script>
</body>
</html>


以下是php文件 文件名:post.php

<?php
$name=$_GET['name'];
$name2=$_POST['name'];
if(!empty($name)){
echo "你使用了get方法";
}else{
echo "你使用了post方法";
}
?>


好了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ajax