006_Ajax发送POST请求

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, 失去焦点

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值