簡體   English   中英

HTML5 onclick按鈕可打開新頁面(但我不希望這樣做)

[英]HTML5 onclick button opens new page (but I don't want it to do that)

我有一個鏈接到數據庫的HTML Web表單。 我必須使用“ type =” submit“才能對必填字段使用驗證功能。執行此操作時,頁面將打開一個新頁面。使用” type =“ button”“不會打開新頁面,但不會無法驗證必填字段。我正在嘗試讓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錯誤。 結果應該是“學生:Doe,John被選修了課程:CS4900。” 尋找有關onclick按鈕問題的幫助,其他所有內容只是為了完全了解環境。 感謝您的協助。

event參數添加到newEnrollment 然后在該方法的頂部,調用event.preventDefault()

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

我將使用偵聽器注冊事件處理程序:

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

我認為您已經使事情復雜化了。 試試這個, target="_self"

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

問題是使用表格。 通過刪除form和fieldset標記並使用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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM