HTML5 onclick按钮打开新页面(但我不希望它这样做)

时间:2014-05-23 19:31:00

标签: javascript html5

我有一个链接到数据库的HTML网页表单。我必须使用" type ="提交"为了使用必要字段的验证功能。当我这样做时,页面打开一个新页面。使用"键入="按钮""不会打开新页面但不验证必填字段。我试图让AJAX将来自servlet的响应插入当前页面而不打开新页面。这是HTML表单。

<form id="EnrollmentForm">
  <p><i>Please complete the form. Mandatory fields are marked with a </i><em>*</em></p>
  <fieldset>
    <legend>New Course Enrollment</legend>
    <label for="StudentID"> Student ID <em>*</em></label>
    <input ID="StudentID" name = "StudentID" autofocus placeholder="12345" required><br>
    <label for="CourseID"> Course ID <em>*</em></label>
    <input id="CourseID" name="CourseID" placeholder="CS4900" required><br>
  </fieldset>
  <p><input onclick="newEnrollment();" type="submit" value="Enroll"></p>
  <p id="result"></p>
</form>

newEnrollment()函数是javascript。

function newEnrollment() {
    validateForm();
    if (validateForm()){
        document.getElementById("result").innerHTML = "The request has been sent.";
        var studentID = document.getElementById("StudentID").value;
        var courseID = document.getElementById("CourseID").value;
        var dataToSend = "?StudentID=" + studentID + "&CourseID=" + courseID;
        req.open("GET", "http://localhost/examples/servlets/servlet/NewEnrollment" + dataToSend, true);
        req.onreadystatechange = handleServerResponse;
        req.send(); 
    }
 }

function handleServerResponse() {
    if ((req.readyState == 4) && (req.status == 200)) {
            var result = req.responseText;
            document.getElementById("result").innerHTML = result;
   }
 }

我将包含Java servlet仅供参考。 SQL语句在未正确结束时返回错误,但我想解决的问题是提交时的新页面。

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;

public class NewEnrollment extends HttpServlet {
  public void doGet(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {

// class to write out to the log files
   ServletContext sc = getServletContext();
   response.setContentType("text/html");
   PrintWriter out = response.getWriter();

// Get the Data from the Database 
   try {
Class.forName("oracle.jdbc.OracleDriver");
    System.out.println("Driver loaded");
    String url="jdbc:oracle:thin:@localhost:1521:CS3600";
    String user = "XXXXXXX";
    String pwd = "XXXXXXX";
    String Course_ID = request.getParameter("CourseID");
    String Student_ID = request.getParameter("StudentID");

    Connection DB_mobile_conn = DriverManager.getConnection(url,user,pwd);
    System.out.println("Database Connect ok");//STUDENT_SEQ.CURRVAL
    PreparedStatement prep_stmt = DB_mobile_conn.prepareStatement("INSERT INTO ENROLLMENT VALUES (?, ?)");
    prep_stmt.setString(1,Course_ID);
    prep_stmt.setString(2,Student_ID);
    prep_stmt.executeUpdate();

    String query = "select Student.Student_Last_Name, Student.Student_First_Name, Courses.Course_Name"+
        " from Courses,enrollment,student where enrollment.Student_ID = '"+Student_ID+
        "' and enrollment.course_id = '"+Course_ID+"' and student.student_id = enrollment.student_id"+
        " and courses.course_ID = enrollment.course_ID;";
    Statement query_stmt=DB_mobile_conn.createStatement();
    ResultSet query_rs=query_stmt.executeQuery(query);
    query_rs.next();

    String result = "Student: "+query_rs.getString(1)+", "+query_rs.getString(2)+
        " was enrolled in course: "+query_rs.getString(3)+".";
    query_rs.close();
    query_stmt.close();     
    out.println(result);

  } catch (Exception exp) {
    out.println("Exception = " +exp);
    System.out.println("Exception = " +exp);
  } 
}

public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws IOException, ServletException
    {
        doGet(request, response);
    }
}

准备好的声明有效。该查询返回SQL错误。 结果应该是 &#34;学生:Doe,John参加了课程:CS4900。&#34; 只需寻求onclick按钮的帮助,其他一切只是为了完全了解环境。感谢您的帮助。

3 个答案:

答案 0 :(得分:0)

event添加newEnrollment参数。然后在该方法的顶部,调用event.preventDefault()

function newEnrollment(event) {
    event.preventDefault();
    .
    .
    .
}

我会使用一个监听器来注册事件处理程序:

form = document.getElementById("EnrollmentForm");
form.addEventListener('submit', newEnrollment, false);

答案 1 :(得分:0)

我认为你让事情变得复杂了。试试这个,target="_self"

参考http://www.w3schools.com/tags/att_a_target.asp

答案 2 :(得分:0)

问题在于使用表单。通过删除表单和字段集标记并使用onclick按钮,它允许innerHTML写回页面。这个解决方案不会执行验证,但我不再需要这样做,所以这样做。

<div> 
  <p><i>Enroll a student in a course. </i></p>

    <legend>New Course Enrollment</legend>
    <label for="StudentID"> Student ID </label>
    <input ID="StudentID" name = "StudentID" autofocus placeholder="12345"><br>
<label for="CourseID"> Course ID </label>
    <input id="CourseID" name="CourseID" placeholder="CS4900"><br>

  <p><button id="zero" onclick="newEnrollment()">Enroll</button></p>
  <p id="result"></p>
</div>