The following example uses the get method of jquer's Ajax function for asynchronous requests.
The result is: click the button to check whether the entered username is available.
<1> download jquery. js and create a folder named jquery under the project name webroot. Put jquery. js in this folder.
<2> Create a JSP with the following code:
<% @ Page Language = "Java" contenttype = "text/html; charset = UTF-8" pageencoding = "UTF-8" %> <! Doctype HTML public "-// W3C // dtd html 4.01 transitional // en" "http://www.w3.org/TR/html4/loose.dtd"> <HTML>
<3> Web. xml configuration in WEB-INF
<servlet> <servlet-name>jqueryAjaxGetServlet</servlet-name> <servlet-class>com.web.ajax.JQueryAjaxGetServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>jqueryAjaxGetServlet</servlet-name> <url-pattern>/servlet/JQueryAjaxGetServlet</url-pattern> </servlet-mapping>
<4>: Write servlet. The servlet code is as follows:
Package COM. web. ajax; import Java. io. ioexception; import Java. io. printwriter; import javax. servlet. servletexception; import javax. servlet. HTTP. httpservlet; import javax. servlet. HTTP. httpservletrequest; import javax. servlet. HTTP. httpservletresponse; public class jqueryajaxgetservlet extends httpservlet {@ overrideprotected void Service (httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {request. setcharacterencoding ("UTF-8"); response. setcontenttype ("text/html; charset = UTF-8"); response. setheader ("cache-control", "No-Cache"); printwriter out = response. getwriter (); string username = request. getparameter ("name"); string Password = request. getparameter ("password"); If ("zhangsan ". equals (username) {// here is out. print is not out. printlnout. print ("unavailable"); // out. the content in print () will be output to the callback function} else {out. print ("available");} Out. flush (); out. close ();}}
Run the command to check the effect.
The post method in jquery Ajax is very similar to the get method.
$. Get () is changed to $. Post ().