我希望创建一个简单的脚本来动态存储信息,而无需刷新或重定向到另一个页面。在来到这里之前,我已经高低寻求答案,并且我遵循了。
但是,我仍然无法获取它来存储数据,因为我不知道哪里出错了。另外,我想问一下success: function(msg)
success: function(msg)
非常感谢!
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>Staff Registration</title> </head> <body> <%-- HTTP header --%> <%response.addHeader("Cache-Control","no-cache"); response.addHeader("Pragma","no-cache"); response.addHeader("Expires","0"); %> <%-- Javascript --%> <script type="text/javascript" src="jquery-1.11.2.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $('#Register').click(function(e) { e.preventDefault(); $.ajax({ url: "StaffRegAuth.jsp", type: "post", data: { username: $('#username').val(), password: $('#password').val(), userGroup: $('#userGroup').val() }, success: function(msg) { alert(msg); } }); }); }); </script> <%-- Main body --%> <h1 align="center"> Account Registration: </h1> <div align="center"> <table style="width = 30%" > <tr> <td> User Name: </td> <td><input type="text" id="username"></td> </tr> <tr> <td> Password: </td> <td><input type="password" id="password"></td> </tr> <tr> <tr> <td> User Group: </td> <td><select name = "userGroup" id="userGroup"> <option value="1">Administrator </optin> <option value="2">Clerk </optin> <option value="3">Operations </optin> <option value="4">Sales </optin> </select></td> </tr> <tr> </table> <input type="submit" value="Register" id="Register"> </div> </body> </html>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title></title> </head> <body> <%-- Imports --%> <%@ page import="java.sql.*"%> <%@ page import="java.util.*"%> <%@page import="javax.servlet.*" %> <%@page import="javax.servlet.http.*" %> <%-- HTTP header --%> <%response.addHeader("Cache-Control","no-cache"); response.addHeader("Pragma","no-cache"); response.addHeader("Expires","0"); %> <%-- Variables that will be written --%> <% String sUsername = request.getParameter("username"); String sPassword = request.getParameter("password"); int sUserGroup = Integer.parseInt(request.getParameter("userGroup")); %> <%-- Creating new staff account - writing --%> <% try{ Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); String conURL= "jdbc:odbc:HOD_DATA"; Connection con = DriverManager.getConnection(conURL); Statement st = con.createStatement(); int status = st.executeUpdate("insert into Staff(username, password, user_group) values('"+sUsername+"','"+sPassword+"',"+sUserGroup+")"); if(status>0){ //out.println("Update sucessful"); } else{ //out.println("Update unsuccessful"); } st.close(); con.close(); } catch(Exception e){ out.println(e); } %> </body> </html>
调试:使用Firebug检查传递给服务器的值。确保提交了正确的ajax请求。
希望能帮助到你。