JS封裝Ajax請求(不同資料格式的請求頭設定)--FROM:學校大學生活動中心預約系統
###JS封裝Ajax請求
####1.GET
獲取xmlHttp物件
function createXMLHttp() { var xmlHttp; if(window.XMLHttpRequest) { xmlHttp = new XMLHttpRequest(); } if(window.ActiveXObject) { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); if(!xmlHttp) { xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); } } return xmlHttp; }
傳送GET請求:
//當頁面載入完成時判斷使用者是不是已經登入
window.onload= function () {
getisloginxmlHttp=createXMLHttp();
var url = "/stuactorder/user/getislogin";
getisloginxmlHttp.open("GET", url, true);
getisloginxmlHttp.onreadystatechange = getislogincallback;
getisloginxmlHttp.send(null);
}
在回撥方法中判斷後端是否響應成功並獲取響應資料:
function getislogincallback(){
if (getisloginxmlHttp.readyState == 4) {
if (getisloginxmlHttp.status == 200) {
var result = getisloginxmlHttp.responseText; //響應成功
}
}
}
####2.通過URL進行POST
獲取xmlHttp物件
function createXMLHttp() { var xmlHttp; if(window.XMLHttpRequest) { xmlHttp = new XMLHttpRequest(); } if(window.ActiveXObject) { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); if(!xmlHttp) { xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); } } return xmlHttp; }
傳送POST請求:
//更新學期資訊
function setschweek(){
var weeksum=document.getElementById("weeksum").value;
var schstart=document.getElementById("schstart").value;
setschweekxmlHttp=createXMLHttp();
var url = "/stuactorder/weekinfo/init?weeksum="+weeksum+"&schstart="+schstart;
setschweekxmlHttp.open("POST", url, true);
setschweekxmlHttp.onreadystatechange = setschweekcallback;
setschweekxmlHttp.send(null);
}
####3.POST資料(JSON)
POST有一定格式的資料時,需要設定傳送編碼和封裝相應的請求頭資訊,以下是POST傳送Json字串的配置:
function login(){
var loginname=document.getElementById("loginname");
var loginpassword=document.getElementById("loginpassword");
xmlHttp=createXMLHttp();
//封裝json
var jsonreq={
loginname:loginname.value,
password:loginpassword.value
};
var jsondate = JSON.stringify(jsonreq);
var url = "/stuactorder/user/login";
xmlHttp.open("POST", url, true);
xmlHttp.setRequestHeader("cache-control","no-cache");
//指定傳送的編碼xmlHttp.setRequestHeader("contentType","text/html;charset=uft-8")
//設定請求頭資訊,設定為傳送json字串
xmlHttp.setRequestHeader("Content-Type", "application/json");
xmlHttp.onreadystatechange = logincallback;
xmlHttp.send(jsondate);
}
####4.POST其他型別的資料的請求頭配置
用Ajax方式提交表單,決定編碼型別的是請求頭中Content-Type,不同的值對應不同的提交和回撥處理方式。
在前端不同的框架中,Content-Type有不同的引數寫法,這裡只介紹XMLHttpRequest方式,其他JQuery和AngularJS的寫法參照(https://segmentfault.com/a/1190000004982390)
XMLHttpRequest物件用於向後端收發資料請求,現代瀏覽器都支援(IE要用ActiveXObject實現相同功能,本文就不討論了)。
後續程式碼將假設已經獲得了XMLHttpRequest物件,其名為req。下面將介紹XMLHttpRequest物件用常見的五種Content-Type傳送資料的方式。
(1)application/x-www-form-urlencoded
這種Content-Type要求資料按照key1=value1&key2=value2的格式傳送給後端,且其中的特殊字元需要轉義成%HH的形式。
首先,需要用encodeURIComponent()函式編碼表單資料,程式碼如下:
/* data引數為表單資料組成的物件,dataToSend為待發送給後端的資料 */
var tempArr = [];
for (var key in data) {
if (data.hasOwnProperty(key)) {
tempArr.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]));
}
}
var dataToSend = tempArr.join('&');
接著,設定請求頭部的Content-Type,傳送資料,程式碼如下:
req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
req.send(dataTosend);
(2)multipart/form-data
這種Content-Type型別多用來提交檔案,我們採用HTML5的FormData物件來構建提交的資料。
(3)text/plain
如果請求頭部沒有設定Content-Type,且資料既不是FormData也不是XML Document,則Content-Type預設為text/plain。
這種方式的程式碼很簡單,直接傳送字串即可,程式碼如下:
req.send('...(此處是字串格式的資料)');
(4)application/json
JSON格式的資料,後端和各種移動端都很方便處理,用這種MIME型別時,需要將資料物件轉換成JSON串。
首先,轉換資料成JSON串;然後,設定請求頭部的Content-Type,就可以發資料了:
req.send( JSON.stringify(data) );