記錄學習Ajax,主要來源於傳智播客於洋的學習視頻資料
AJAX : 異步 javascript和 XML
AJAX :帶來用戶體驗改變,是web優化一種主要手段AJAX = DHTML (HTML、CSS、JavaScript ) + XMLHttpRequest 對象
傳統web交互模型,瀏覽器直接將請求發送給服務器,服務器回送響應,直接發給瀏覽器, Ajax交互模型,瀏覽器首先將請求 發送 Ajax引擎(以XMLHttpRequest爲核心),AJax引擎再將請求發送給 服務器,服務器回送響應先發給Ajax引擎,再由引擎傳給瀏覽器顯示
1、同步交互模式,客戶端提交請求,等待,在響應回到客戶端前,客戶端無法進行其他操作
2、異步交互模型,客戶端將請求提交給Ajax引擎,客戶端可以繼續操作,由Ajax引擎來完成與服務武器端通信,當響應回來後,Ajax引擎會更新客戶頁面,在客戶端提交請求後,用戶可以繼續操作,而無需等待 。
下面一個簡單的Ajax的入門案例,同時也是苦逼的HelloWorld的。
1.創建XMLHttpRequest對象
2.將狀態觸發器綁定到一個函數
3.使用open方法建立與服務器的連接
4.向服務器端發送數據
5.在回調函數中對返回數據進行處理
<script type="text/javascript">
//創建XMLHttpRequest
function createXMLHttpRequest() {
try {
xmlHttp = new XMLHttpRequest();
} catch (tryMS) {
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (otherMS) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
xmlHttp = null;
// 這裏可以報一個錯誤,無法獲得 XMLHttpRequest對象
}
}
}
return xmlHttp;
}
//第一步創建XMLHttpRequest
var xmlHttp = createXMLHttpRequest();
//第二部 將狀態觸發器綁定到一個函數
xmlHttp.onreadystatechange = function() {
// 第五步,響應返回後執行
// 狀態依次 是 0 - 4
// 0 未初始化
// 1 正在加載
// 2 已經加載
// 3 交互中
// 4 響應完成
if (xmlHttp.readyState == 4) {
// 判斷數據是否正確
if (xmlHttp.status == 200) {
// 響應有效
alert("響應返回了..." + xmlHttp.responseText);
}
}
};
//第三步,建立連接
//get
//xmlHttp.open("GET","helloword?name=賬上"); //// helloworld 代表 Servlet URL
//post
xmlHttp.open("POST","helloword");
//第四步 發送數據
//xmlHttp.send(null); get
//post
xmlHttp.setRequestHeader("CONTENT-TYPE","application/x-www-form-urlencoded");
xmlHttp.send("name=李四");
</script>
下面來寫一個servlet來和頁面交互
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
System.out.println("ajax相應收到了。。。。。。。。");
//獲得參數
String name = request.getParameter("name");
name = new String(name.getBytes("ISO-8859-1"),"utf-8");
System.out.println(name);
response.setContentType("text/plain;charset=utf-8");
response.getWriter().print("ajax響應數據");
}
這樣一個簡單的helloworld就好了
總結一下,
XMLHttpRequest
方法: open send
屬性:
onreadystatechange :狀態回調函數
responseText/responseXML :服務器的響應字符串
status:服務器返回的HTTP狀態碼
statusText: 服務器返回的HTTP狀態信息
readyState :對象狀態
客戶端向服務器提交數據
1、get方式發送數據
xmlHttp.open("GET","url?key=value"); // 參數已經在url上
xmlHttp.send(null);
2、post方式發送數據
xmlHttp.open("POST","url"); // 不需要寫參數
xmlHttp.setRequestHeader("CONTENT-TYPE","application/x-www-form-urlencoded"); // post發送參數前,需要設置編碼格式
xmlHttp.send("name=xxx&pwd=xxx"); // 發送post數據
回調函數編寫
if(xmlHttp.readyState == 4){
// 判斷數據是否正確
if(xmlHttp.status == 200){
// 響應有效
...
}
}