我正在開發一個使用java的web應用程序,目前我需要將表單信息從servlet發送到servlet,並將反饋發送回servlet的html頁面。特別是當用戶連接我想從servlet返回我的數據庫中的所有用戶的用戶名和密碼 從我搜查的唯一方法正確地做到這一點是通過使用ajax,但我似乎無法能夠使其工作。使用ajax提交表單並從servlet接收信息
從HTML網頁摘錄
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="form" method="post" action="signIn">
<input id="uname" name="uname" class="form-control" type="text">
<input id="pass" name="pass" class="form-control" type="password">
<input id="button1" class="btn btn-primary" type="submit" value="Sign In" />
</form>
<div id=result></div>
我的servlet(SingIn.java)目前看起來像這樣
public class SignIn extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String uname = request.getParameter("uname");
String pass = request.getParameter("pass");
Registration.setOnline(uname);
try {
// loading drivers for mysql
Class.forName("com.mysql.jdbc.Driver");
// creating connection with the database
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/ted", "root", "root");
PreparedStatement ps = con.prepareStatement("select * from user");
ResultSet rs = ps.executeQuery();
out.println("<table>");
while (rs.next()) {
uname = rs.getString(1);
pass = rs.getString(2);
out.println("<tr><th>" + uname +"</th><th>"+ pass + "</th></tr>");
}
out.println("</table>");
} catch (Exception e) {
e.printStackTrace();
}
RequestDispatcher res = request.getRequestDispatcher("html/index.html");
res.include(request, response);
}
}
我的web.xml的部分看起來像這樣
<servlet-mapping>
<servlet-name>SignIn</servlet-name>
<url-pattern>/signIn</url-pattern>
</servlet-mapping>
因爲它是我能訪問servlet,並有提交表單的信息,但servlet的響應在頁面的頂部顯示出來,而我需要它在「結果」格顯示。 我認爲這是最好使用Ajax和JavaScript,但我真的需要這部分幫助
更新 目前,我試圖在阿賈克斯 $(文件)。就緒像這樣(函數(){
// Add an event that triggers when the submit
// button is pressed.
$("#button1").click(function() {
// Get the text from the two inputs.
var uname = $("#uname").val();
var pass = $("#pass").val();
// Ajax POST request.
$.post('signIn',{"uname": uname, "pass": pass},
function() { // on success
$(#result).innerHTML=(not sure what);
});
});
你的Ajax代碼在哪裏? –