AJAX教程

Ajax Java示例

要创建 ajax 示例,您需要使用任何服务器端语言,例如Servlet,JSP,PHP,ASP.Net等。在这里,我们使用JSP生成服务器端代码。
在此示例中,我们仅打印了以下表格:

使用jsp创建ajax示例的步骤

您需要执行以下步骤:
加载org.json.jar文件 创建输入页面以接收任何文本或数字 创建服务器端页面以处理请求 在web.xml文件中提供条目

创建页面接收文本或数字

在此页面中,我们创建了一个从用户获取输入的表单。当用户单击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>

创建服务器端页面以处理请求

在此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示例输出
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4