Welcome 微信登录
编程资源 图片资源库 蚂蚁家优选 PDF转换器

首页 / 操作系统 / Linux / jQuery异步功能实例

jQuery确实是一个很好的JavaScript框架,今天利用闲暇时间给大家一个借助jQuery异步实现校验用户名的唯一性的例子:代码1——index.jsp文件:<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
   <head>
   <title>如何使用jquery实现异步验证用户名的唯一性</title>
  <script type="text/javascript" src="<%=basePath%>js/jquery-1.8.3.min.js"></script>
  <script type="text/javascript">
   function checkUserName(){
    $.ajax({
        url : "<%=basePath%>JqueryAjaxCheckUserNameServlet", //(默认: 当前页地址) 发送请求的地址
     type: "post", //(默认: "get") 请求方式 ("post" 或 "get"), 默认为 "get"。注意:其它 http请求方法,如 put和 delete也可以使用,但仅部分浏览器支持。
     timeout:10,//设置请求超时时间(毫秒)。此设置将覆盖全局设置。
     async:true,//(默认: true) 默认设置下,所有请求均为异步请求。如果需要发送同步请求,请将此选项设置为 false。注意,同步请求将锁住浏览器,用户其它操作必须等待请求完成才可以执行。
     contentType:"application/x-www-form-urlencoded",//(默认: "application/x-www-form-urlencoded") 发送信息至服务器时内容编码类型。默认值适合大多数应用场合。
     data: "userName="+$("#userName").val(),//发送到服务器的数据。将自动转换为请求字符串格式。GET 请求中将附加在 URL 后。查看 processData 选项说明以禁止此自动转换。必须为 Key/Value 格式。如果为数组,jQuery 将自动为不同值对应同一个名称。如 {foo:["bar1", "bar2"]} 转换为 "&foo=bar1&foo=bar2"。
     dataType:"json",/*预期服务器返回的数据类型。如果不指定,jQuery 将自动根据 HTTP 包 MIME 信息返回 responseXML 或 responseText,并作为回调函数参数传递,可用值:
          *"xml": 返回 XML 文档,可用 jQuery 处理。
          *"html": 返回纯文本 HTML 信息;包含 script 元素。
          *"script": 返回纯文本 JavaScript 代码。不会自动缓存结果。
          *"json": 返回 JSON 数据 。
          *"jsonp": JSONP 格式。使用 JSONP 形式调用函数时,如 "myurl?callback=?" jQuery 将自动替换 ? 为正确的函数名,以执行回调函数。
          */
     success: function(json, textStatus){//如果调用servlet成功,响应200。请求成功后回调函数。这个方法有两个参数:服务器返回数据,返回状态(可以缺省)。
      console.log(textStatus);
      var flag = json.flag;
       if(flag == "true"){
       $("#showUserName").html("<font size="2" color="green">&nbsp;&nbsp;用户名有效!</font>");
      }else if(flag == "false"){
          $("#showUserName").html("<font size="2" color="red">&nbsp;&nbsp;用户名已被使用!</font>");
      }
     },
     error:function (XMLHttpRequest, textStatus, errorThrown) {//如果调用servlet出现问题,响应非200(这里响应405)。通常情况下textStatus和errorThown只有其中一个有值 。(默认: 自动判断 (xml 或 html)) 请求失败时将调用此方法。这个方法有三个参数:XMLHttpRequest 对象,错误信息,(可能)捕获的错误对象。
           console.log(textStatus);
           $("#showUserName").html("<font size="2" color="red">&nbsp;&nbsp;请求发送失败!</font>");
        } 
    });
   }
  </script>
   </head>
 
   <body>
     <center style="margin-top: 10%"><font style="color: red;font-size: 18pt;font-weight: bold;">如何使用jquery实现异步验证用户名的唯一性</font><br><br>
            用户名:<input type="text" id="userName" name="userName" size="27" onblur="checkUserName();">
     <font size="2" id="showUserName">&nbsp;&nbsp;*用户名必填,具有唯一性。</font>
  </center>
 </body>
</html>代码2——JqueryAjaxCheckUserNameServlet.java文件:package com.ghj.packagofserlet;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 JqueryAjaxCheckUserNameServlet extends HttpServlet { private static final long serialVersionUID = 6387744976765210524L; public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
  doPost(request,response);
 }
 
 public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
  try{
   response.setCharacterEncoding("UTF-8");
   request.setCharacterEncoding("UTF-8");
   System.out.println(1/0);//故意出现异常,以检查index.jsp中error方法是否可用
   PrintWriter out = response.getWriter();
   String userName=request.getParameter("userName");//获取“用户名”
   if("admin".equals(userName)) {
    out.write("{"flag":"false"}");//“false”表示用户名不可用。
   } else {
    out.write("{"flag":"true"}");//“true”表示用户名可用。
   }
   out.flush();
   out.close();
  }catch (Exception e) {
   e.printStackTrace();
   response.setStatus(405);//此时将执行index.jsp中error方法。
  }
 }
}代码3——web.xml文件:<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns="http://java.sun.com/xml/ns/javaee"
 xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
 http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">   <servlet>
     <servlet-name>JqueryAjaxCheckUserNameServlet</servlet-name>
     <servlet-class>com.ghj.packagofserlet.JqueryAjaxCheckUserNameServlet</servlet-class>
   </servlet>   <servlet-mapping>
     <servlet-name>JqueryAjaxCheckUserNameServlet</servlet-name>
     <url-pattern>/JqueryAjaxCheckUserNameServlet</url-pattern>
   </servlet-mapping>
 
   <welcome-file-list>
     <welcome-file>index.jsp</welcome-file>
   </welcome-file-list>
</web-app>说明:上面的例子用到了jquery-1.8.3.min.js文件,该文件可在下面的下载资源中找到。1、如何使用jQuery实现异步验证用户名的唯一性(本工程旨在研究如何使用jquery实现异步验证用户名的唯一性的功能。 本工程编码方式:UTF-8)2、jQuery实现表单异步提交(本工程为Java Web工程,演示了如何使用Jquery实现表单的异步提交!)------------------------------------------分割线------------------------------------------免费下载地址在 http://linux.linuxidc.com/用户名与密码都是www.linuxidc.com具体下载目录在 /2014年资料/8月/12日/jQuery异步功能实例/下载方法见 http://www.linuxidc.com/Linux/2013-07/87684.htm------------------------------------------分割线------------------------------------------jQuery权威指南 PDF版中文+配套源代码 http://www.linuxidc.com/Linux/2013-10/91059.htmjQuery实战 中文PDF+源码 http://www.linuxidc.com/Linux/2013-09/90631.htm《jQuery即学即用(双色)》 PDF+源代码 http://www.linuxidc.com/Linux/2013-09/90383.htm锋利的jQuery(第2版) 完整版PDF+源码 http://www.linuxidc.com/Linux/2013-10/91527.htmjQuery完成带复选框的表格行高亮显示 http://www.linuxidc.com/Linux/2013-08/89406.htmjQuery基础教程(第4版) PDF 完整高清版+配套源码 http://www.linuxidc.com/Linux/2014-03/98162.htm--------------------------------------分割线 --------------------------------------jQuery 的详细介绍:请点这里
jQuery 的下载地址:请点这里本文永久更新链接地址:http://www.linuxidc.com/Linux/2014-08/105464.htm