测试页面:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>AJax Post</title> <script type="text/javascript"> function checkName(){ var xml_request = new XMLHttpRequest(); var namevalue = document.getElementById("name").value; //xml_request.open("post","CheckServlet?name=zhangsan",true); xml_request.open("post","CheckServlet",true); //必须写到 send之前 xml_request.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); xml_request.send("name="+namevalue); xml_request.onreadystatechange = function(){ if(xml_request.readyState==4&&xml_request.status==200){ var name1 = xml_request.responseText; //关注此处 alert(name1+"sd\nda"); alert(namevalue); alert(name1==(namevalue+"\r\n")) document.getElementById("result").innerHTML=xml_request.responseText; } } } </script> </head> <body> <input type="text" name="name" id="name" onblur="checkName();"> <span id="result"></span> </body> </html>
Servlet进行处理代码:
package com.bwie; import java.io.IOException; import java.io.PrintWriter; import java.net.URLEncoder; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class CheckServlet extends HttpServlet { public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { response.setContentType("text/html"); request.setCharacterEncoding("UTF-8"); //设置请求编码 response.setCharacterEncoding("UTF-8");//设置响应编码 System.out.println(request.getCharacterEncoding());; System.out.println(response.getCharacterEncoding()); String name = request.getParameter("name"); System.out.println(name); //new String("ab".getBytes("ISO-8859-1"),"UTF-8"); //URLEncoder.encode("abc","UTF-8"); PrintWriter out = response.getWriter(); out.println(name); out.flush(); out.close(); } }