说到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