要?jiǎng)?chuàng)建ajax示例,需要使用服務(wù)器端語(yǔ)言,例如:Servlet,JSP,PHP,ASP.Net等。這里使用JSP來(lái)生成服務(wù)器端代碼。
在這個(gè)例子中,只是打印給定數(shù)字的表。
需要按照以下步驟操作:
• 加載org.json.jar文件。
• 創(chuàng)建輸入頁(yè)面以接收文本或數(shù)字。
• 創(chuàng)建服務(wù)器端頁(yè)面以處理請(qǐng)求。
• 在web.xml文件中提供條目。
第一步:加載org.json.jar文件
下載此示例,在WEB-INF/lib目錄中包含了org.json.jar文件。
第二步:創(chuàng)建輸入頁(yè)面以接收文本或數(shù)字
在此頁(yè)面中,我們創(chuàng)建了一個(gè)從用戶獲取輸入的表單。當(dāng)用戶單擊showTable按鈕時(shí),將調(diào)用sendInfo()函數(shù)。在這個(gè)函數(shù)中編寫(xiě)了所有的ajax代碼。
只要準(zhǔn)備好狀態(tài)更改,我們就調(diào)用了getInfo()函數(shù)。它通過(guò)innerHTML屬性動(dòng)態(tài)地將返回的數(shù)據(jù)寫(xiě)入網(wǎng)頁(yè)。
文件: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>
第三步:創(chuàng)建服務(wù)器端頁(yè)面以處理請(qǐng)求
在這個(gè)jsp頁(yè)面中,我們打印給定數(shù)字的表格。
文件: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>
輸出結(jié)果如下: