很多时候大家都习惯了jquery的ajax方法,或者axios,今天突然想起了js的原生方法,温故知新,所以想写一写
jquery ajax方法:
$.ajax({
type:'POST',
url:' http://xxxxxxx',
data:{
},
dataType:'json',
success:function(res){
},
error:function(err){
}
})
原生js get请求:
//对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请求:
//对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)
}
}