When developing JavaScript, sometimes it is time-consuming to call a function. This is an Asynchronous Method: Set a callback function to listen to the execution status of the function, after the time-consuming function is executed, the preset return function is automatically triggered. Jquery provides a deferred object to solve this type of problem.
$. Ajax returns a deferred object. The following is an example:
On the ccc.html page, we will display a drop-down list of related books (Multiple choices). After selecting the items, click submit at the bottom. In the Click Event of the button, we use the deferred object to wait for the remote server to respond. If the response is successful, the content returned by the remote server is displayed below; otherwise, the failure information is displayed.
Ccc.html File
<HTML>
Loginservlet. Java File
Import Java. io. ioexception; import Java. io. printwriter; import Java. util. date; import javax. servlet. servletexception; import javax. servlet. annotation. webservlet; import javax. servlet. HTTP. httpservlet; import javax. servlet. HTTP. httpservletrequest; import javax. servlet. HTTP. httpservletresponse; @ webservlet (name = "loginservlet", urlpatterns = "/login") public class loginservlet extends httpservlet {@ overridepubli C void Service (httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {response. setcontenttype ("text/html; charset = UTF-8"); string [] books = request. getparametervalues ("books"); printwriter writer = response. getwriter (); writer. println ("current time:" + new date (1375066895226l) + "<br/>"); writer. println ("your favorite books are: <br/>"); writer. println ("<ol>"); try {thread. sleep (10 * 1000); // wait for 10 seconds before responding} catch (interruptedexception e) {e. printstacktrace ();} If (null! = Books) {for (string book: Books) writer. println ("<li>" + book + "</LI>");} writer. println ("</OL> ");}}
The following figure shows the effect.
This is the website's ccc.html page
This is the page after selecting a book and clicking the button. It can be seen that the remote server has returned.
It is worth noting that this page can still be operated within 10 seconds after waiting for the remote server to return. For example, here I click the Java book again, it indicates that the done and fail callback functions of the deferred object are asynchronous.