Ajax:提交資料
阿新 • • 發佈:2018-11-13
一、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");
}