說到Ajax,只要有過前端開發經驗的童鞋必定都不陌生,大都知道它就是一種與後端之間的通訊技術,經過這個神奇的傢伙,咱們不用像傳統表單那樣填完信息一點提交就呼啦呼啦跳轉了。Ajax最大的一個優點就是經過異步請求達到局部刷新的目的,這樣就大大提升了用戶體驗。但是Ajax就是咱們平時使用得最多的jQuery中的$.ajax()嗎?答案確定不是的,那咱們就來一塊兒看看原生的Ajax究竟長啥樣把!javascript
Ajax技術的核心是XMLHttpRequest對象(簡稱XHR)php
function getXhr(){ if (typeof XMLHttpRequest != 'undefined') { return new XMLHttpRequest(); } }
xhr.open('get', 'example.php', false);
xhr.open('GET', url); xhr.send(null);
xhr.open('POST', url); xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xhr.send(stringData);
xhr.onreadystatechange = function(){ if(xhr.readyState == 4){ if(xhr.status == 200){ document.getElementById("unInfo").innerHTML = xhr.responseText; } } }
function getXhr(){ if (typeof XMLHttpRequest != 'undefined') { return new XMLHttpRequest(); } } var xhr = getXhr(); //GET請求 xhr.open('GET', '/user/checkLogin'); xhr.send(null); xhr.onreadystatechange = function(res) { if (xhr.readyState == 4) { if (xhr.status == 200) { console.log(JSON.parse(xhr.responseText)) } } }
function getXhr(){ if (typeof XMLHttpRequest != 'undefined') { return new XMLHttpRequest(); } } var xhr = getXhr(); var stringData = { uname: '123', password: '123', code: '' } stringData = JSON.stringify(stringData); //POST請求 xhr.open('POST', '/user/login'); xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xhr.send(stringData) xhr.onreadystatechange = function(res) { if (xhr.readyState == 4) { if (xhr.status == 200) { console.log(JSON.parse(xhr.responseText)) } } }
參考文章:html