使用ajax向服务器发送请求

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="js/jquery-1.8.3.min.js" ></script>
<script type="text/javascript">
    //页面加载完成后
    $(function(){
        $("#username").blur(function(){
            var usernamevalue = $("#username").val();
            //alert(usernamevalue)
            var url = "/jquery_ajax/load";
            $.ajax({
                url:url,
                data:{'username':usernamevalue},
                type:"post",
                dataType:"html",
                success:function(data){
                    $("#username_span").html(data);
                }
            });
        });
    });
</script>
</head>
<body>
    <input type="text" name="username" id="username" />
    <span id="username_span"></span><br />
</body>
</html>

服务端java代码编写

package com.niwotaxuexiba.servlet;

import java.io.IOException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoadServlet extends HttpServlet {
    public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException{
        //解决乱码问题
        response.setContentType("text/html;charset=utf-8");
        //得到用户名
        String username = request.getParameter("username");
        //判断用户名是否可用
        if(("tom").equals(username)){
            //用户名不可以使用
            response.getWriter().write("用户名被占用");
        }else{
            //用户名可以使用
            response.getWriter().write("用户名可以使用");
        }
    }
    public void doPost(HttpServletRequest request,HttpServletResponse response) throws IOException{
        doGet(request,response);
    }
}

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" 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">
  <display-name>jquery_ajax</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <display-name>LoadServlet</display-name>
    <servlet-name>LoadServlet</servlet-name>
    <servlet-class>com.niwotaxuexiba.servlet.LoadServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>LoadServlet</servlet-name>
    <url-pattern>/load</url-pattern>
  </servlet-mapping>
</web-app>