原生javaScript Ajax方法

不少时候你们都习惯了jquery的ajax方法,或者axios,今天忽然想起了js的原生方法,温故知新,因此想写一写javascript

jquery ajax方法:java

$.ajax({

        type:'POST',

        url:' http://xxxxxxx',

        data:{

            },

        dataType:'json',

        success:function(res){

        },

        error:function(err){

        }
})

 

原生js get请求:jquery

//对ie低版本浏览器作兼容处理
 if (window.XMLHttpRequest){
       var xhr=new XMLHttpRequest();
    }else if (window.ActiveXObject){
       var xhr=new ActiveXObject("Microsoft.XMLHTTP");
  }
 xhr.open('GET','http://www.baidu.com');
 xhr.send()
 xhr.onreadystatechange = function () { 
      if (xhr.readyState == 4 && xhr.status == 200) { 
            console.log(xhr.responseText)
        }
     }

js post请求:ios

//对ie低版本浏览器作兼容处理
 if (window.XMLHttpRequest){
       var xhr=new XMLHttpRequest();
    }else if (window.ActiveXObject){
       var xhr=new ActiveXObject("Microsoft.XMLHTTP");
  }
 xhr.open('POST','http://www.baidu.com');
 xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
 xhr.send(data)
 xhr.onreadystatechange = function () { 
      if (xhr.readyState == 4 && xhr.status == 200) { 
            console.log(xhr.responseText)
        }
     }
相关文章
相关标签/搜索