阿賈克斯(AJAX)
AJAX :Asynchronous JavaScript and XML 異步的javascript 和xml
優點 : 在不重新加載整個頁面的情況下,可以與服務器交換數據並更新部分數據
不需要任何的瀏覽器插件,但需要用戶允許javascript在瀏覽器上執行
應用:運用XHTML+CSS來表達資訊 javascript操作DOM(Document Object Model)
XMLHttpRequest是ajax的基礎
現代瀏覽器(IE7、FIREFOX、CHROME、safari 還有Opera)舊代(IE5、IE6)
語法不同 :variable = new XMLHttpRequest();
Variable = new ActiveXObject(“Microsoft.XMLHTTP”);
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
向服務器發送請求: XMLHttpRequest對象的open() send
xmlhttp.open(method, url, async):method--get或者post類型
Url --文件在服務器上的位置
Async:boolean值 true (異步) false 同步
xmlhttp. Send(String) :String ---post請求
Get方法更簡單方便 post:無法使用緩存文件、發送大量數據
例子:get:xmlhttp.open(“get” , “demo_get.html” , true);
xmlhttp.send();
Post: xmlhttp.open(“post” , “demo_post.html” , true);
xmlhttp.setRequestHeader(“content-type” ,“application/x-www-form-urlencoded”);
//向請求添加HTTP頭 header 頭的名稱 value 值
xmlhttp.send(“fname = Bill & lname = gates”);
Async = true : 請規定在響應處於onreadystatechange 時間中 的就緒狀態
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById(“muDiv”).innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open(“get” , “test.txt” , true);
xmlhttp.send();
服務器響應: XMLHttpRequest對象的responseText 或者 responseXML
字符串響應數據 XML形式響應
每當readystate改變的時候,就會觸發onreadystatechange事件
Readystate存有XMLHttpRequest的狀態 0-4
0: 請求未初始化 1:服務器連接已建立
2:請求已接受 3:請求處理中 4:請求已完成,且響應已就緒
Status: 200 “OK” ; 404: 未找到頁面
例子:
function showHint(str)
{
var xmlhttp;
if (str.length==0)
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","gethint.asp?q="+str,true);
xmlhttp.send();
}
代碼解釋: 如果輸入框為空 length==0 清空txthint占位符的內容,並退出函數
如果不為空,執行任務:
創建XMLHttpRequest對象 ,當服務器響應就緒時執行函數
把請求發送到服務器上的文件, 註:url中帶有個參數q
例子:簡化版
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="js/ajax.js"></script>
<script type="text/javascript">
window.onload=function() {
document.getElementById("username").onblur=function() {
sendAjax("POST", "register.sxt", "username="+this.value, function(result) {
// 向span中顯示信息
if(result == "yes") {
document.getElementById("uspan").innerHTML="√";
} else {
document.getElementById("uspan").innerHTML="×";
}
});
};
};
</script>
</head>
<body>
<input type="text" name="username" id="username" /><span id="uspan"></span>
</body>
</html>
Js
function sendAjax(method, url, body, success) {// 鉤子函數, 回調函數
var xmlHttp;
if(window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
} else {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState == 4) {
if(xmlHttp.status == 200 || xmlHttp.status == 304) {
// 成功時調用函數
success(xmlHttp.responseText);
}
}
};
xmlHttp.open(method, url);
if(method == "POST") {
// 設置請求頭信息, 表示提交數據時按照表單的方式提交
xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
}
xmlHttp.send(body);
}
如果加了數據庫內容:
@WebServlet("/register.sxt")
public class RegisterServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String username = req.getParameter("username");
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql = "select count(*) from users where username=?";
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test401", "root", "root");
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, username);
rs = pstmt.executeQuery();
if(rs.next()) {
if(rs.getInt(1)>0) {
resp.getWriter().print("no");
} else {
resp.getWriter().print("yes");
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
rs.close();
pstmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
阿賈克斯(AJAX)