原生js实现ajax方法

2017-10-24 08:05:16来源:CSDN作者:zhanglir333人点击

分享

转自:http://www.jb51.net/article/93037.htm

function ajax(){   varajaxData = {     type:arguments[0].type ||"GET",     url:arguments[0].url ||"",     async:arguments[0].async ||"true",     data:arguments[0].data ||null,     dataType:arguments[0].dataType ||"text",     contentType:arguments[0].contentType ||"application/x-www-form-urlencoded",    beforeSend:arguments[0].beforeSend ||function(){},     success:arguments[0].success ||function(){},     error:arguments[0].error ||function(){}   }  ajaxData.beforeSend()  varxhr = createxmlHttpRequest();    xhr.responseType=ajaxData.dataType;  xhr.open(ajaxData.type,ajaxData.url,ajaxData.async);   xhr.setRequestHeader("Content-Type",ajaxData.contentType);   xhr.send(convertData(ajaxData.data));   xhr.onreadystatechange =function() {      if(xhr.readyState == 4) {        if(xhr.status == 200){        ajaxData.success(xhr.response)      }else{        ajaxData.error()          }  }   function createxmlHttpRequest() {    if(window.ActiveXObject) {      returnnew ActiveXObject("Microsoft.XMLHTTP");   }else if (window.XMLHttpRequest) {      returnnew XMLHttpRequest();    }   function convertData(data){   if(typeof data === 'object' ){     varconvertResult = ""     for(varc in data){        convertResult+= c +"=" + data[c] + "&"        convertResult=convertResult.substring(0,convertResult.length-1)    returnconvertResult;   }else{    returndata;   }}

使用格式跟jquery的ajax差不多:


123456789101112131415ajax({   type:"POST",  url:"ajax.php",  dataType:"json",  data:{"val1":"abc","val2":123,"val3":"456"},  beforeSend:function(){    //some js code  },  success:function(msg){    console.log(msg)  },  error:function(){    console.log("error")  }})

最新文章

123

最新摄影

闪念基因

微信扫一扫

第七城市微信公众平台