使用post方式的ajax
<%@ 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>
<base href="<%=basePath%>">
<title>My JSP 'index.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>
<script type="text/javascript">
//当用户使用文本框输入内容的时候验证内容是否存在
function check(){
var xhr;
//IE旧版本浏览器的时候
if(window.XMLHttpRequest){//判断是否存在
xhr=new XMLHttpRequest();//创建异步对象
}else{
xhr=new ActiveObject('Microsoft.XMLHTTP');
}
var name=document.getElementsByName('user')[0].value;
/*1、 根据步骤创建ajax的验证 */
//2、回调函数 当提交上去之后 响应结果符合要求的时候
/* xhr.onreadystatechange =callBack;
//3、设置URL和请求方式
var url="IndexServlet?name="+name;
xhr.open("GET", url, true);//创建HTTP的一个新的请求 还没有提交的
xhr.send(null); //4、发送请求,只要是get提交方式参数就是null */
//之前是ajax get提交方式
//2、设置回调函数
xhr.onreadystatechange=callBack;
//3、设置URL 和请求方式
var url="IndexServlet";
xhr.open("POST", url, true);//true表示异步请求
var data="name="+name;//参数名字
xhr.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded")//设置请求头的编码方式 二进制数据多重编码
//post提交方式必须要加上的
//表示客户端提交给服务器文本的编码方式
//4、发送请求
xhr.send(data); //get是通过URL传递值 post是通过Http头部信息传递
function callBack(){
if(xhr.readyState==4 && xhr.status==200){
//这样才能证明ajax提交成功并且被处理了
//alert(1)测试ajax的输出
var result= xhr.responseText;
alert(result);
}
}
}
</script>
<form action="IndexServlet" method="post" enctype="">
用户名:<input type="text" name="user" οnblur="check()"/>
<input type="submit" value="提交"/>
</form>
</body>
</html>
IndexServlet code:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setCharacterEncoding("utf-8");
System.out.println("进入IndexServlet");
String name=new String(request.getParameter("name").getBytes("iso-8859-1"),"utf-8");
System.out.println(name);
//把数据发送到jsp里面
PrintWriter out= response.getWriter();
out.print(name);
}