一,前言:
前文,我們介紹了ajax的原理和核心內容,主要講的是ajax從前端到后端的數據傳遞的整個過程。
真正的核心就是這段代碼:
var xhr = new XMLHTTPRequest(); xhr.open("method", "url", "async"); xhr.send(null); xhr.onreadystatechange = function(){ if(xhr.readystate == 4){ if(xhr.status == 200){ console.log(xhr.responseText) } } }
一個對象(XMLHTTPRequest對象)、
兩個方法(包括open("method", "url", "async")方法和send(content)方法)、
三個屬性(readystate表示當前請求狀態,status表示http請求狀態碼,responseText表示服務器反饋內容),
當然還有一個事件——onreadystatechange ,是在readystate狀態改變時觸發的事件。具體的內容請點擊鏈接Ajax工作原理。
二,正文:
先來看看jQuery中Ajax方法的使用:
$.ajax({ type: "GET", //訪問服務器的方式,GET/POST url: "test.json", //url表示訪問的服務器地址 data: {username: "", content: ""}, //data表示傳遞到后台的數據,使用鍵值對形式傳遞 async: true, //true表示異步,false表示同步 success: function(data){ console.log(data) }, error: function(err){ console.log(err) } });
那么我們想要封裝成類似JQuery的形式,供調用,怎么辦呢?
function $Ajax(opt){ opt = opt || {}; opt.type = opt.type || "post"; opt.url = opt.url || ""; opt.async = opt.async || true; opt.data = opt.data || null; opt.success = opt.success || function(){}; opt.error = opt.error || function(){}; var xhr = new XMLHTTPRequest(); var params = {}; for(var key in opt.data){ params.push(key + "=" + opt.data[key]); } var sendData = params.join("&"); if(opt.type.toUpperCase() == "GET"){ xhr.open(opt.type, opt.url + "?" + sendData, opt.async); xhr.send(null); }else{ xhr.open(opt.type, opt.url, opt.async); xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=utf-8"); xhr.send(sendData); } xhr.onreadystatechange = function(){ if(xhr.readystate == 4){ if(xhr.status == 200){ opt.success && opt.success(xhr.responseText); }else{ opt.error && xhr.error(xhr.status); } } } }
已經封裝好了,接下來就是調用了,就像jQuery那樣使用就行:
$Ajax({ type: "GET", url: "test.json", data: {username: "", content: ""}, async: true, success: function(responseText){ console.log(responseText) }, error: function(status){ console.log(status) } });
二,結語:
已經很晚了,沒有進行測試,也沒有詳細進行注釋,有時間再完善吧。
詳細看這一篇:Ajax工作原理和原生JS的ajax封裝