原生JS封装Ajax
2017-08-16 09:49
316 查看
这里写一个原生JS封装ajax的demo。
以下是php文件 文件名:post.php
好了。
<!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基础——如何用原生js封装一个ajax函数
- 原生JS封装Ajax插件(同域&&jsonp跨域)
- 使用原生JS封装Ajax
- 原生JS封装ajax 传json,str,excel文件上传提交表单(推荐)
- 原生JS封装AJAX请求
- 原生js封装ajax代码
- 原生js封装ajax,实现跨域请求
- 原生js封装ajax 案例
- 原生JS封装ajax方法
- 原生JS封装Ajax插件(同域&&jsonp跨域)
- 城市三级联动 AJAX-原生js封装
- 利用原生js封装一个ajax api(一)
- 将ajax请求封装为一个对象(原生js)
- 原生js封装ajax方法
- 第110天:Ajax原生js封装函数
- 原生js实现对Ajax的封装(模仿jquery)
- js原生Ajax的封装与使用
- 原生js实现对Ajax的封装(仿jquery)
- 用原生JS对AJAX做简单封装的实例代码
- 原生js封装ajax:传json,str,excel文件上传表单提交