1. 使用我们的Ajax动态WEB项目
2. 编写ajax_post.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Ajax post请求获取字符串响应</title>
</head>
<body>
<form action="" method="post">
用户名: <input type="text" name="userName" autofocus="autofocus" onBlur="showHint(this.value)" /><span id="txtHint"></span><br />
密码: <input type="password" name="password" /><br />
<input type="submit" value="提交" />
</form>
<script type="text/javascript">
function showHint(userName)
{
if(userName == undefined)
{
document.getElementById("txtHint").innerHTML="请输入用户名";
return;
}
// 创建XMLHttpRequest对象。XMLHttpRequest对象用于和服务器交换数据。
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function()
{
// 4请求完成, 200服务器返回状态OK。
if(xmlHttp.readyState == 4 && xmlHttp.status == 200)
{
// 获取字符串响应
document.getElementById("txtHint").innerHTML=xmlHttp.responseText;
}
}
// 使用XMLHttpRequest对象的open()和send()方法, 发送post请求到服务器。
xmlHttp.open("post", "register.action", true);
xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded; charset=UTF-8");
xmlHttp.send("userName="+encodeURIComponent(userName));
}
</script>
</body>
</html>
3. 编写RegisterAction.java
package com.lywgames.ajax;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class RegisterAction extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String userName = req.getParameter("userName");
String result = "";
if("zhangsan".equals(userName) || "lisi".equals(userName)) {
result = "用户名已注册";
}
if(null == userName || userName.length() < 3) {
result = "用户名不合法";
}
// 响应客户端的内容类型是text/html 编码是UTF-8(包含字符编码和网页编码)
resp.setContentType("text/html;charset=UTF-8");
resp.getWriter().write(result);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
4. 配置web.xml
5. 运行项目, 输入用户名lisi, 失去焦点