将ajax封装成函数

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:

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