GET方法:
function btn_get_click(){ var httpRequest = new XMLHttpRequest(); httpRequest.onreadystatechange = handleResponse; // httpRequest.open("GET", "/user/login?user_name=" + encodeURIComponent(username) + "&password=" + // encodeURIComponent(password)); httpRequest.open("GET", "/course/schedule?termno=0&week=0"); httpRequest.send(null); } function handleResponse(e) { if (e.target.readyState == XMLHttpRequest.DONE){ document.getElementById("result").innerHTML = e.target.responseText; var responseTextJson = JSON.parse(e.target.responseText); alert(responseTextJson.length); alert(responseTextJson[0].classroom); // alert(responseTextJson.DATAINFO[0].PROJ_NAME); } }
GET方法是明文的,處理上面的類似用戶名密碼的其實要用POST方法.(非明文方式)
PSOT:
function clickLoin() { var yonghu = document.getElementById("username").value;//獲取用戶名 var mima = document.getElementById("password").value;//獲取密碼 var httpRequest = new XMLHttpRequest(); httpRequest.onreadystatechange = handleResponse; var getloin ="username="+yonghu+"&&password="+mima; httpRequest.open("post", "/login"); //以下這句在POST時要加上 httpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); httpRequest.send(getloin); } function handleResponse(e) { if (e.target.readyState == XMLHttpRequest.DONE){ // var responseTextJson = JSON.parse(e.target.responseText); alert(e.target.responseText); } }
兩者的區別:
補充:(題外話)
后端post接口開發者的想法:
post函數定義了請求的地址,參數,還有一個回調函數。
而post的概念就是
“我執行的時候,需要你給我地址和參數,然后我執行完了,就完了,但是如果開發人員你,需要用到我返回的數據和狀態,你要用,怎么辦呢?
那沒關系,不是還有一個回調函數嗎?我再提供一個回調函數給你,至於你想怎么用,就用這個回調函數實現,於是我只把返回的數據,狀態放在參數列表里面,並且下一個”執行“你外部函數的命令,
具體怎么實現,你要怎么用,是你開發人員的事了。