Jquery——Ajax实例

来源:互联网 发布:广告终结者 for mac 编辑:程序博客网 时间:2024/04/29 23:52
 

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
  <script src="js/jquery-1.6.4.js"type="text/javascript"></script>
<script type="text/javascript" src="js/find.js" ></script>
  <script type="text/javascript">
 $(function (){
 
$("#tb").click(function(){
check();

 if($("#result").text()=="用户名已经存在"){
alert("用户名已经存在");
return false;
}
//$("#myform").submit();
 });
 });
 
  </script>
 
    <base href="<%=basePath%>">
   
    <title>My JSP 'MyJsp.jsp' starting page</title>
   
 <meta http-equiv="pragma" content="no-cache">
 <meta http-equiv="cache-control" content="no-cache">
 <meta http-equiv="expires" content="0">   
 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
 <meta http-equiv="description" content="This is my page">
 <!--
 <link rel="stylesheet" type="text/css" href="styles.css">
 -->

  </head>
 
  <body>
  <form action="" id="myform">
    <input type="text" id="username" onblur="check()"/>
    <div id="result"></div>
  
    <input type="submit" value="提交" id="tb" />
    </form>
  </body>
</html>

Find.js——

function check(){
 //获得文本框的值
 var z=$("#username").val();
 $.post("Check",{username:z},function(data){
  $("#result").html(data);
 })
}

Check类——

package com.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 Check extends HttpServlet {

 
 public void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {

 this.doPost(request, response);
 }

 
 public void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {

  response.setContentType("text/html");
  response.setCharacterEncoding("utf-8");
  PrintWriter out = response.getWriter();
  String username=request.getParameter("username");
  if(username==null){
   out.print("用户名不能为空");
  }else
  if(username.equals("123")){
   out.print("用户名已经存在");
  }else{
   out.print("用户名不存在");
  }
  out.flush();
  out.close();
 }

}


 

 


 

原创粉丝点击