一、Get請求
1. 創建XmlHttpRequest 對象。 這部分創建對象的代碼,由於需要針對不同的瀏覽器, 需要做出判斷,並且還沒有什麼提示, 所以大家可以不用自己寫。 往後直接拷貝即可。
function ajaxFunction() {
var xmlHttp;
try {
xmlHttp = new XMLHttpRequest();
} catch (e) {
try {// Internet Explorer
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
}
}
}
return xmlHttp;
}
2. 發送請求
function doGet() {
//不帶數據,直接請求。
//獲取 xmlhttprequest 對象
var request = ajaxFunction();
// http://localhost:8080/day16/demo01.jsp
//http://localhost:8080/day16/DemoServlet01
/*
參數一: 請求類型 GET or POST
參數二: 請求的路徑
參數三: 是否異步, true or false
*/
request.open("GET", "Demo01", true);
//發送請求。
request.send();
--------------------------------以下帶上數據--------------------------------------
//獲取 xmlhttprequest 對象
var request = ajaxFunction();
// 參數一: 執行 get 請求 , 參數二 : 請求的地址 , 參數三: 是否是異步請求。
request.open("GET", "Demo01?name=zhangsan&age=18", true);
//發送請求
request.send();
}
二、Post請求
Post請求和Get請求基本相似,區別就在於數據傳輸方式不同。Get方式是直接在地址的後面拼接的,但是Post的方式是通過send方式傳輸過去的,並且還要設置一個請求頭。基本上,如果明白了Http的協議,那麼對Post請求的代碼理解起來就不是那麼困難了。
1. 創建XmlHttpRequest 對象。 這部分創建對象的代碼,由於需要針對不同的瀏覽器, 需要做出判斷,並且還沒有什麼提示, 所以大家可以不用自己寫。 往後直接拷貝即可。
function ajaxFunction() {
var xmlHttp;
try {
xmlHttp = new XMLHttpRequest();
} catch (e) {
try {// Internet Explorer
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
}
}
}
return xmlHttp;
}
2、發送請求
function doPost(){
//不帶數據,直接請求。
//獲取 xmlhttprequest 對象
var request = ajaxFunction();
// 參數一: 執行 get 請求 , 參數二 : 請求的地址 , 參數三: 是否是異步請求。
request.open("POST", "Demo01", true);
//發送請求。
request.send();
--------------------------------以下帶上數據--------------------------------------
//獲取 xmlhttprequest 對象
var request = ajaxFunction();
// 參數一: 執行 get 請求 , 參數二 : 請求的地址 , 參數三: 是否是異步請求。
request.open("POST", "Demo01", true);
//設置請求頭,其實就是表示傳輸的是一個經過url編碼的form表單數據
request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
request.send("name=zhangsan&age=18");
}