要創建ajax示例,需要使用伺服器端語言,例如:Servlet,JSP,PHP,ASP.Net等。這裏使用JSP來生成伺服器端代碼。
在這個例子中,只是列印給定數字的表。
使用jsp創建ajax示例的步驟
需要按照以下步驟操作:
- 加載
org.json.jar
檔。 - 創建輸入頁面以接收文本或數字。
- 創建伺服器端頁面以處理請求。
- 在
web.xml
檔中提供條目。
第1步:加載org.json.jar檔
下載此示例,在WEB-INF/lib
目錄中包含了org.json.jar
檔。
第2步:創建輸入頁面以接收文本或數字
在此頁面中,我們創建了一個從用戶獲取輸入的表單。當用戶單擊showTable
按鈕時,將調用sendInfo()
函數。在這個函數中編寫了所有的ajax代碼。
只要準備好狀態更改,我們就調用了getInfo()
函數。它通過innerHTML屬性動態地將返回的數據寫入網頁。
檔:table1.html
<html>
<head>
<script>
var request;
function sendInfo() {
var v = document.vinform.t1.value;
var url = "index.jsp?val=" + v;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
request = new ActiveXObject("Microsoft.XMLHTTP");
}
try {
request.onreadystatechange = getInfo;
request.open("GET", url, true);
request.send();
}
catch (e) {
alert("Unable to connect to server");
}
}
function getInfo() {
if (request.readyState == 4) {
var val = request.responseText;
document.getElementById('amit').innerHTML = val;
}
}
</script>
</head>
<body>
<marquee>
<h1>This is an example of ajax</h1>
</marquee>
<form name="vinform">
<input type="text" name="t1">
<input type="button" value="ShowTable" onClick="sendInfo()">
</form>
<span id="amit"> </span>
</body>
</html>
第3步:創建伺服器端頁面以處理請求
在這個jsp頁面中,我們列印給定數字的表格。
檔:index.jsp
<%
int n=Integer.parseInt(request.getParameter("val"));
for(int i=1;i<=10;i++)
out.print(i*n+"<br>");
%>
檔:web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>table1.html</welcome-file>
</welcome-file-list>
</web-app>
輸出結果如下 -
上一篇:
AJAX如何工作
下一篇:
Ajax Java資料庫示例