- ajax操作中以post方式提交异步请求
a) 创建xhr
var xhr = new XMLHttpRequest();
b) 发送请求
xhr.open("post","url");
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");//在post请求中有这句话,get请求中没有,此为二者的区别。
xhr.send("name=suns&password=123456&…");
解释: 为什么在post方式提交数据时 需要指定 application/xxxx…?
答案:
<form method="post" action="" enctype="application/x-www-form-urlencoded">
<input type="text" name="name"/>
……
</form>
表单中默认有enctype属性,只有有这个enctype属性,才可以使用request.getParameter(“name”)获取到name的值。
若做文件上传,则enctype=”multipart/form-data”
在xhr操作中 没有了form 就没有enctype属性, 所以必须手工设置
c) 处理响应
xhr.onreadystatechange = function(){
if(xhr.readySate==4 && xhr.status==200){
xhr.responseText;
}
}
实例代码
//首先需要引入jquery-1.8.3.js插件,放在WebContent下面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="jquery-1.8.3.js"></script>
<script type="text/javascript">
$(function(){
//当name丢失焦点时调用此函数
$("#name").blur(function(){
//1.获得文本框中的内容
var name = $(this).val();
//2.发送ajax异步请求
var xhr;
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest();
}else{
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.open("post","CheckName");
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xhr.send("name="+name);
//xhr处理相应
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
/* alert(xhr.responseText); */
$("#msg").text(xhr.responseText);
}
});
});
});
</script>
<title>注册</title>
</head>
<body>
<table>
<tr>
<td>UserName</td>
<td><input type="text" name="name" id="name"/><span id="msg"></span></td>
</tr>
<tr>
<td>UserPassword</td>
<td><input type="text" name="password" id="password"/><span id="msg"></span></td>
</tr>
<tr>
<td>UserEmail</td>
<td><input type="text" name="email" id="email"/><span id="msg"></span></td>
</tr>
<tr>
<td><input type="button" value="注册"/></td>
</tr>
</table>
</body>
</html>