码迷,mamicode.com
首页 > Web开发 > 详细

将ajax封装成函数

时间:2020-03-25 21:32:25      阅读:86      评论:0      收藏:0      [点我收藏+]

标签:efi   判断   res   函数   ==   text   send   pos   llb   

function ajax({url,type,data,callback}){
  if (type==undefined){
  type="get"
}
// 1 创建异步对象 var xhr=new XMLHttpRequest(); if(type=="get"&&data!==undefined){ // 如果请求参数不为空且为get,就把参数加到url上 url+="?"+data; } // 2 创建请求 xhr.open(type,url,true); // 3 接收响应数据 xhr.onreadystatechange=function(){ if(xhr.readyState==4&&xhr.status==200){ var result=xhr.responseText; callback(result) } } // 判断请求类型并发送请求 if(type=="post"){ xhr.setRequestHeader(‘Content-Type‘,"application/x-www-form-urlencoded"); } if(type=="post"){ xhr.send(data); }else{ xhr.send(); } }

这样在页面中可以通过调用ajax函数来直接使用ajax:

 

将ajax封装成函数

标签:efi   判断   res   函数   ==   text   send   pos   llb   

原文地址:https://www.cnblogs.com/codexlx/p/12570247.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!