不少時候你們都習慣了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) } }