一个简单的Ajax例子
今天寫個Ajax的小例子,我在項目中并沒有用到過Ajax,看到Ajax很流行,今天寫個demo,希望大家指點
創建一個全局的XMLrequest對象,該對象的方法如下
open():建立到服務器的新請求。
send():向服務器發送請求。
abort():退出當前請求。
readyState:提供當前 HTML 的就緒狀態。
responseText:服務器返回的請求響應文本。Onreadystatechange屬性的五種狀態:
- 0:請求沒有發出(在調用 open() 之前)。
- 1:請求已經建立但還沒有發出(調用 send() 之前)。
- 2:請求已經發出正在處理之中(這里通常可以從響應得到內容頭部)。
- 3:請求已經處理,響應中通常有部分數據可用,但是服務器還沒有完成響應。
jsp代碼如下:
<html>
?<head>
???<script language="javascript" type="text/javascript">
?var XMLrequest = false;
?try {
??request = new XMLHttpRequest();
?} catch (trymicrosoft) {
??try {
???XMLrequest = new ActiveXObject("Msxml2.XMLHTTP");
??} catch (othermicrosoft) {
???try {
????XMLrequest = new ActiveXObject("Microsoft.XMLHTTP");
???} catch (failed) {
????XMLrequest = false;
???}
??}
?}
?if (!XMLrequest){
??alert("Error initializing XMLHttpRequest!");
?}
?function callServer() {
??? // Get the city and state from the web form
??? var name = document.getElementById("name").value;
??? var pwd = document.getElementById("pwd").value;
??? // Only go on if there are values for both fields
??? if ((name == null) || (name == "")) return;
??? if ((pwd == null) || (pwd == "")) return;
??? // Build the URL to connect to
??? var url = "http://localhost:8080/ajaxproject/servlet/Login?name=" + escape(name) + "&pwd=" + escape(pwd);
//escape() 方法,它用于轉義不能用明文正確發送的任何字符。比如,電話號碼中的空格將被轉換成字符 %20
??? // Open a connection to the server
??? XMLrequest.open("GET", url, true);
??? // Setup a function for the server to run when it's done
??? XMLrequest.onreadystatechange = updatePage;
??? // Send the request
??? XMLrequest.send(null);
??}
?function updatePage() {
??? if (XMLrequest.readyState == 4) {
????? var response = XMLrequest.responseXML;
????? var re = response.getElementsByTagName("name")[0].firstChild.nodeValue;
????? document.getElementById("xianshi").value = re ;
??? }
??}
</script>
?</head>
?<body>
??<form action="" method="get">
???<input type="text" name="name" onChange="callServer();"/>
???<input type="password" name="pwd" onChange="callServer();"/>
???<input type="submit" name="submit" onClick=""/>
??</form>
??<form action="">
???<input type="text" name="xianshi" id="xianshi" value=""/>
??</form>
?</body>
</html>
servetlet代碼如下:
String name = request.getParameter("name");
??response.setContentType("text/xml;charset=utf-8");
??response.setHeader("Cache-Control", "no-cache");
??String xml = "<response>";
??if(name == null || name.trim().equals("")){
???xml +="<name>null</name>";
??}else {
???xml+="<name>"+name+"</name>";
??}
??xml+="</response>";
??PrintWriter out = response.getWriter();
??out.print(xml.toString());
??out.close();
轉載于:https://www.cnblogs.com/xingzhen/archive/2011/05/30/2063153.html
總結
以上是生活随笔為你收集整理的一个简单的Ajax例子的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 15款提高工作效率的工具分享
- 下一篇: Ext4核心组件Grid的变化及学习(3