Using jQuery to implement Ajax operations
I want to achieve the Ajax page without refresh effect, but it is a bit troublesome to use Ajax code directly, so I want to use jQuery to achieve it. jQuery nicely encapsulates the core object of Ajax, XMLHTTPRequest. So it is very convenient to use.
First, create the server-side code, here use Servlet to implement server-side data processing; the code is as follows:
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 设置编码格式 resp.setContentType("text/html;charset=UTF-8"); // 创建输出对象 PrintWriter out = resp.getWriter(); // 得到请求参数 String name = req.getParameter("uname"); // 判断 if (name == null || name.length() == 0) { out.println("用户名不能为空!"); } else { // 判断 if (name.equals("cheng")) { out.println("用户名["+ name +"]已存在!请使用其他用户名!"); } else { out.println("用户名[" + name + "]尚未存在!您可以注册!"); } } }
Then, create a JSP page. To use jQuery, you must introduce the jQuery library, which is a Javascript file, into the page. In addition, you need to introduce a custom Javascript file, as follows:
<!-- 引入Javascript文件 --> <script type="text/javascript" src="js/jquery-1.2.6.js"></script> <script type="text/javascript" src="js/verify.js"></script>
The JSP page only needs a text box, an ordinary button and a blank DIV layer. The DIV is used to display the processing results returned by the server; the click event of the button triggers the verify() method. As follows:
<body> <center> 用户名:<input type="text" id="uname" name="uname" /> <br /> <input type="button" name="btnVerify" value="验证" onclick="verify()" /> <br /> <div id="result"> </div> </center> </body>
Note: There is no need to use a form to submit data in Ajax mode, so there is no need to write the