Implementation of test countdown based on AJAX technology and automatic submission of paper _ajax related

Source: Internet
Author: User
Tags current time

1. Overview

When developing the network examination system, the examination time and automatically submits the examination paper is the essential function. Because the quiz paper cannot be refreshed during the answer process, you need to use Ajax to implement the no refresh operation. Run this instance, access the Prepare for examination page index.jsp, on this page, click the "Start Quiz" button, will open a new window to show the beginning of the exam page, as shown in Figure 10.1, the page will automatically time, when the exam is over, will automatically raise the test paper.

2. Technical points

It is mainly implemented by using AJAX asynchronous submission technology and servlet technology. The timings displayed on the test page are set in the servlet and require the continuous request servlet through an asynchronous submission of Ajax to obtain the latest timing data returned by the server. To facilitate maintenance and reuse of code, the Ajax request method can be encapsulated into a JS file, which can be used as a public method and can be invoked directly in a program.

3. Specific implementation code

Build the XMLHttpRequest object and the request method in the JS file, as shown in the following code:

/** * Build XMLHttpRequest object and Request Server * @param reqtype: Request type (GET or post) * @param URL: Server address * @param async: Asynchronous Request * @param resfun: Ring 
Expected callback function * @param parameter: Request parameter * @return: XMLHttpRequest object/Function HttpRequest (reqtype,url,async,resfun,parameter) {
var request = null; if (window. XMLHttpRequest) {//non IE browser, create XMLHttpRequest Object request = new XMLHttpRequest ();} else if (window. ActiveXObject) {//ie Browser, create XMLHttpRequest object var arrsignatures = ["Msxml2.xmlhttp", "Microsoft.XMLHTTP", " Microsoft.XMLHTTP "," MSXML2. xmlhttp.5.0 "," MSXML2. xmlhttp.4.0 "," MSXML2. xmlhttp.3.0 "," MSXML2. 
XMLHTTP "]; for (var i = 0; i < arrsignatures.length i++) {request = new ActiveXObject (arrsignatures[i]); if (Request | | typeof
(Request) = = "Object") break; } if (Request | | typeof (Request) = = "Object") {if (reqtype.tolowercase () = "POST") {//post-submitted Request.open (Reqtype, U RL, True);
Open Server connection//set MIME type Request.setrequestheader ("Content-type", "application/x-www-form-urlencoded"); Request.onreadystatechange = RESfun; Sets the callback function that handles the response parameter = encodeURI (parameter); The parameter string is encoded request.send (parameter); Send request} else{//Submit URL in Get way = url+ "?" 
+parameter; Request.open (Reqtype, URL, true); Open Server Connection Request.onreadystatechange = Resfun; Response callback function request.send (NULL); Send request} else{alert ("This browser does not support ajax! 
" );
}
return request;  }

(1) Create a new index.jsp page, which is the initial page that the user accesses. The button's OnClick event invokes a JavaScript function that opens the test window, which includes a "Start quiz" button in the page, with the following key code:

function ShowWindow () {window.open (' startexam?action=startexam ', ', ', ' Width=750,height=500,scrollbars=1 ');

(2) Create a new Servlet implementation class named Startexam, which uses the start time and the remaining time of the creation test. In this class, create a global variable examtime that records the test time, the value of which is set in Web.xml, and the key code is as follows:

<servlet>
<servlet-name>StartExam</servlet-name>
<servlet-class> com.lh.servlet.startexam</servlet-class>
<init-param>
<param-name>examtime</ param-name>
<param-value>20</param-value>
</init-param>

(3) in the Startexam class, write a method for forwarding the page to the Start test page Startexam (). The key code is as follows:

public void Startexam (httpservletrequest request,httpservletresponse response)
throws Servletexception, ioexception{
HttpSession session = Request.getsession ();
Request.setattribute ("Time", examtime); Save test time
Session.setattribute ("startTime1", New Date (). GetTime ());//Save the number
of milliseconds for the current time Request.getrequestdispatcher ("startexam.jsp"). Forward (request, response);

(4) New showstarttime.jsp page for output timing start time. The key code is as follows:

<% @page contenttype= "text/html" pageencoding= "GBK"%>

(5) Create a new showremaintime.jsp page for the output timer remaining time. The key code is as follows:

<% @page contenttype= "text/html" pageencoding= "GBK"%>

(6) The New Start test Page startexam.jsp page, in which the Startexam class is requested by invoking the Ajax request method to get the test start time and the remaining time. The key code is as follows:

 var request1= false; var request2 = false;//request servlet get start time function Showstarttime () {VA
R url = "Startexam"; Here you need to add &nocache= "+new Date (). GetTime (), otherwise there will be no time to walk automatically in the case of Var parameter=" action=showstarttime&nocache= "+new
Date (). GetTime (); 
Request1 = HttpRequest ("post", Url,true,callbackfunc,parameter); }//Callback Functions function Callbackfunc () {if (request1.readystate==4) {if (Request1.status =) {showstarttimediv.innerhtml
=request1.responsetext; {}}//Request the servlet to obtain the remaining time function showremaintime () {var url = "Startexam"; var parameter= "Action=showremaintime&nocach
E= "+new Date (). GetTime (); 
Request2 = HttpRequest ("post", Url,true,callbackfunc_r,parameter); 
}//Callback Functions function Callbackfunc_r () {if (request2.readystate==4) {if (Request2.status =) {h=request2.responsetext;
Showremaintimediv.innerhtml=h; H=h.replace (/\s/g, "");
Removes the Unicode whitespace character showremaintimediv.innerhtml=h in the string;
if (h== "00:00:00") {Form1.submit ();}} }
} 

(7) In order to achieve the automatic timing of the page load, you need to use the Window.setinterval () method to call the Showstarttime () function and showremailtime in the <body> tab of the start test page by using the OnLoad event () function, the key code is as follows:

<body onload= "Showstarttime () showremaintime ();" onkeydown= "KeyDown ()" >

The above is a small set to introduce Ajax technology based on the countdown to the test and automatic submission of the relevant knowledge of the test paper, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.