AJAX教程

Ajax 评论示例

在Java中使用AJAX的评论表单示例

在此示例中,我们正在创建一个表单以发布评论。表单数据保存在数据库中,所有已发布评论的列表显示在评论表单下方。

使用Java中的AJAX创建评论表单示例的步骤

请按照以下步骤操作:
在数据库中创建表 加载org.json.jar文件 创建评论表单 创建服务器端页面以保存表单数据并打印所有已发布的评论

在数据库创建表

中创建表在此示例中,我们使用的是oracle 10g数据库。该表的结构如下所示:
评论表单表
" usercomment"表的id字段是自动递增的。

加载org.json.jar文件
下载此示例,我们已将org.json.jar文件包含在WEB-INF/lib目录中。

创建评论表单

在此页面中,我们创建了一个表单,该表单从用户那里获取输入。当用户单击"发表评论"按钮时,将调用 postComment()函数。我们已经在此函数内编写了所有ajax代码。
index.html
<!DOCTYPE html>
<html>
<head>
<script>
var request;
function postComment(){
var comment=document.commentform.comment.value;
var email=document.commentform.email.value;
var url="index.jsp?comment="+comment+"&email="+email;
if(window.XMLHttpRequest){
request=new XMLHttpRequest();
}
else if(window.ActiveXObject){
request=new ActiveXObject("Microsoft.XMLHTTP");
}
try{
request.onreadystatechange=function(){
if(request.readyState==4){
var val=request.responseText;
document.getElementById('mylocation').innerHTML=val;
}
}//end of function
request.open("GET",url,true);
request.send();
}catch(e){alert("Unable to connect to server");}
}
</script>
</head>
<body>
<h1>Comment Form</h1>
<form name="commentform">
Enter Comment:<br/>
<textarea name="comment" style="width:300px;height:100px" required>
</textarea><br/>
Enter Email:<br/>
<input type="text" name="email" required/><br/><br/>
<input type="button" value="Post Comment" onclick="postComment()">
</form>
<span id="mylocation"></span>
</body>
</html>

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

在此jsp页面中,我们正在编写数据库代码以保存评论并打印所有评论。
index.jsp
<!DOCTYPE html>
<html>
<head>
<style>
div.box{margin:2px;border:1px solid pink;padding:10px;background-color:#e3e3e3}
</style>
</head>
<body>
<%@ page import="java.sql.*" %>
<%
String comment=request.getParameter("comment");
String email=request.getParameter("email");
if(comment==null||email==null||comment.trim().equals("")||email.trim().equals("")){
out.print("<p>Please write comment</p>");
}else{
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
PreparedStatement ps=con.prepareStatement("insert into usercomment(comment1,email) values(?,?)");
ps.setString(1,comment);
ps.setString(2,email);
int i=ps.executeUpdate();
PreparedStatement ps2=con.prepareStatement("select * from usercomment order by id desc");
ResultSet rs=ps2.executeQuery();
out.print("<hr/><h2>Comments:</h2>");
while(rs.next()){
out.print("<div class='box'>");
out.print("<p>"+rs.getString(2)+"</p>");
out.print("<p><strong>By: "+rs.getString(3)+"</strong></p>");
out.print("</div>");
}
con.close();
}catch(Exception e){out.print(e);}
}//end of else
%>
</body>
</html>

输出

ajax评论表单示例输出1
现在写评论和电子邮件ID,然后单击"发布评论"按钮。发表评论的列表将显示在评论表单下方。
ajax评论表单示例输出2
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4