<%@ 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> <meta charset="UTF-8"> <base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</title> </head> <body> <!-- <button onclick="doAjax()">请求ajax</button>--> <div id="myDiv">接收数据:</div> <form name="form1" action="#" method="get"> 用户名:<input type="text" id="uid" name="username" onblur="doAjax()" /> <span id="uspan"></span> 密码:<input type="password" id="pid" name="password"> </form> <script type="text/javascript"> function doAjax() { var userinput = document.getElementById("uid").value; console.log(userinput); //1.创建对象 var xhr = new XMLHttpRequest(); //4.监听readyState的值,接收数据 //只要当readyState的值发生了变化,就调用绑定在onreadystatechange(请求状态改变的事件)上面的函数 xhr.onreadystatechange = function() { if (xhr.readyState == 4) { //status 表示http状态码 200为接收成功 if (xhr.status == 200) { //取数据xhr.responseText服务器响应的文本 //对返回的数据使用DOM进行操作 document.getElementById("uspan").innerHTML = xhr.responseText; } } else { //等数据 document.getElementById("uspan").innerHTML = "<img src='126.gif'>"; } } //2.创建HTTP请求 method、url、是否异步(异步同步) xhr.open("post", "hiservlet", true); //设置http表头 xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded") //3.发送请求 可以是null值 xhr.send("username=" + userinput); } </script> </body> </html>