ajax的使用一直是以jQuery爲主,對於底層的實現有點不明覺厲。做爲一個有追求的前端,這是不能夠接受的。便讓咱們今晚好好走進ajax的心裏世界。前端
ajax 兩大特性:ajax
ajax 請求流程
step-1
首先先創建一個異步請求對象瀏覽器
var httpRequest if(window.XMLHttpRequest) { httpRequest = new XMLHttpRequest(); } else if(window.ActiveXObject) { httpRequest = new ActiveXObject("Microsoft.XMLHTTP"); }
step-2
第一步的httpRequest對象設置已經好了。而後咱們要作的就是設置咱們的請求被響應時的動做緩存
httpRequest.onreadystatechange = function(){ if(httpRequest.readyState === 4) { // everything is good, the response is received } else { // still not ready } }
readyState 說明服務器
Response 屬性閉包
step-3
而後來寫一個簡單的demoapp
<span id="ajaxButton" style="cursor: pointer; text-decoration: underline"> Make a request </span> <script> (function(){ var httpRequest; if (window.XMLHttpRequest) { httpRequest = new XMLHttpRequest(); } else if(window.ActiveXObject) { httpRequest = new ActiveXObject("Microsoft.XMLHTTP"); } if (!httpRequest) { alert('Giving up :( (Cannot create an XMLHTTP instance'); return false; } httpRequest.onreaystatechange = function() { if (httpRequest.readyState === 4) { if (httpRequest.status === 200) { alert(httpRequest.responseText); } else { alert('There was a problem with the request.'); } } } httpRequest.open('GET', url); httpRequest.send(); })() </script>
愛心小貼士:異步
返回的數據爲JSON時,應對數據進行相應的解析url
function alertContents() { if(httpRequest.readyState === 4) { if(httpRequest.status === 200) { var response = JSON.parse(httpRequest.responseText); } else { alert('There was s problem with the request.'); } } }