一、 AJAX
AJAX 是Asynchronous JavaScript And XML(异步的 JavaScript 和 XML)的缩写。
AJAX 不是新的编程语言,而是一种使用现有标准的新方法。
AJAX 是与服务器交换数据并更新部分网页的艺术,在不重新加载整个页面的情况下
1. JavaScript中的AJAX
1.1 使用步骤
1. 创建XMLHttpRequest(存在浏览器差异)
var xmlHttp;
if(window.XMLHttpRequest){
xmlHttp=new XMLHttpRequest();
}else{// ie5,ie6
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
2. 发送请求
xmlHttp.open("GET/POST",url,true);
// 第一个参数:请求方式(GET,POST),
// 第二参数url,第三个参数是否异步请求(一般都是true)
xmlHttp.send();//send可以写参数(post请求使用)
3. 处理响应结果
如需获得来自服务器的响应,请使用 XMLHttpRequest 对象的 responseText 或
responseXML 属性
xmlHttp.onreadystatechange=function(){
if(xmlHttp.readyState==4 && xmlHttp.status==200){
............................
}
注释:onreadystatechange 事件被触发 5 次(0 ‐ 4),对应着 readyState 的每
个变化
1.2 使用
1.2.1 Get请求
login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function checkUserName() {
var username = document.getElementById("username").value;
var xmlHttp;
if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
} else {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
// 2 发送请求
var url = "${pageContext.request.contextPath}/check?username="
+ username;
xmlHttp.open("GET", url, true);
xmlHttp.send();
// 3 处理响应结果
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
document.getElementById("span").innerHTML = xmlHttp.responseText;
}
}
}
</script>
</head>
<body>
<form action="" onsubmit="" method="post">
用户名: <input id="username" name="name" type="text"
placeholder="请输入2-6个字符(字母)" onblur="checkUserName()"><span
id="span"></span> <br> 密码: <input id="password" name="password"
type="password" placeholder="请输入6个字符(数字字母)"> <br> <input
type="submit" value="注册"> <br>
</form>
</body>
</html>
CheckUserName.java (servlet)
package com.hx.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.hx.service.UserService;
import com.hx.service.UserServiceImpl;
@WebServlet("/check")
public class CheckUserName extends HttpServlet {
private static final long serialVersionUID = 1L;
public CheckUserName() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
String username = request.getParameter("username");
UserService uService=new UserServiceImpl();
if (uService.isExistByName(username)) {
response.getWriter().write("<font color='red'>您注册用户名,太受欢迎</font>");
} else {
response.getWriter().write("<font color='green'>可以放心注册</font>");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
UserDaoImpl .java
package com.hx.dao;
import java.sql.SQLException;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import com.hx.bean.User;
import com.hx.utils.BaseDao;
public class UserDaoImpl implements UserDao {
@Override
public User getUserByName(String name) {
User user =null;
QueryRunner runner=new QueryRunner(BaseDao.source);
String sql="select id,name,sex,age from users where name= ? ";
try {
user=runner.query(sql, new BeanHandler<User>(User.class),name);
} catch (SQLException e) {
e.printStackTrace();
}
return user;
}
}
package com.hx.bean;
public class User {
private int id;
private String name;
private String sex;
private int age;
private String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public User() {
}
public User(int id, String name, String sex, int age, String password) {
super();
this.id = id;
this.name = name;
this.sex = sex;
this.age = age;
this.password = password;
}
}
1.2.2 Post请求
<script type="text/javascript">
function checkUserName() {
var username = document.getElementById("username").value;
var xmlHttp;
if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
} else {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
// 2 发送请求
var url = "${pageContext.request.contextPath}/check";
xmlHttp.open("POST", url, true);
//alert(0);
//设置请求头必须在调用open之后
//xmlHttp.setRequestHeader("content‐type","application/x‐www‐form‐urlencoded");
//content‐type首字母c要大写
xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
var param="username="+username;
xmlHttp.send(param);
// 3 处理响应结果
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
document.getElementById("span").innerHTML = xmlHttp.responseText;
}
}
}
</script>
1.2.3 使用ajax提交json
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function checkUserName() {
var username = document.getElementById("username").value;
var xmlHttp;
if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
} else {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
// 2 发送请求
var url = "${pageContext.request.contextPath}/check";
xmlHttp.open("POST", url, true);
//设置请求头必须在调用open之后
//xmlHttp.setRequestHeader("content‐type","application/x‐www‐form‐urlencoded");
//content‐type首字母c要大写
xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
var param="username="+username;
xmlHttp.send(param);
// 3 处理响应结果
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
document.getElementById("span").innerHTML = xmlHttp.responseText;
}
}
}
function register(){
var username = document.getElementById("username").value;
var pwd = document.getElementById("password").value;
var sendData={"name":username,"password":pwd}
//创建XMLHttpRequest
var xmlHttp;
if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
} else {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
var url="${pageContext.request.contextPath}/register";
//发送请求
xmlHttp.open("POST", url, true);
xmlHttp.setRequestHeader("Content-type","application//json");
xmlHttp.send(JSON.stringify(sendData));
// 3 处理响应结果
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
//alert(xmlHttp.responseText);
var content = JSON.parse(xmlHttp.responseText);
if(content.result=="success"){
document.getElementById("span2").innerHTML = "注册成功";
}else{
document.getElementById("span1").innerHTML = "注册失败";
}
}
}
}
</script>
</head>
<body>
<form action="" onsubmit="" method="post">
用户名: <input id="username" name="name" type="text"
placeholder="请输入2-6个字符(字母)" onblur="checkUserName()"><span
id="span"></span> <br> 密码: <input id="password" name="password"
type="password" placeholder="请输入6个字符(数字字母)"> <br> <input
type="button" value="注册" onclick="register()"> <br>
</form>
<span id="span1"></span>
</body>
</html>
package com.hx.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.Gson;
import com.hx.bean.User;
import com.hx.service.UserService;
import com.hx.service.UserServiceImpl;
@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public RegisterServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
ServletInputStream is = request.getInputStream();
byte[] buffer=new byte[1024];
StringBuilder sb=new StringBuilder();
while((is.read(buffer))!=-1) {
sb.append(new String(buffer));
}
String json=sb.toString().trim();
Gson gson=new Gson();
User user=gson.fromJson(json, User.class);
//System.out.println(user);
// 响应json结果
UserService uService=new UserServiceImpl();
if(uService.register(user.getName(), user.getPassword())) {
response.getWriter().write("{"result":"success"}");
}else {
response.getWriter().write("{"result":"error"}");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
2. JQuery中Ajax
编写常规的 AJAX 代码并不容易,因为不同的浏览器对 AJAX 的实现并不相同。这意味着您必须编写额外的代码对浏览器进行测试。不过,jQuery 团队为我们解决了这个难题,我们只需要一行简单的代码,就可以实现 AJAX 功能
2.1 get请求
$.get() 方法
$.get() 方法通过 HTTP GET 请求从服务器上请求数据。
$.get(URL,callback);
必需的 URL 参数规定您希望请求的 URL。
可选的 callback 参数是请求成功后所执行的函数名。
下面的例子使用 $.get() 方法从服务器上的一个文件中取回数据:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery-1.4.1.min.js"></script>
<script type="text/javascript">
$(function(){
$("#username").blur(function(){
var username=$("#username").val();
// 取表单元素的值
var url="${pageContext.request.contextPath}/check?username="+username;
$.get(url,function(data,status){
if(status=="success"){
$("#span").html(data);
}
});
})
})
</script>
</head>
<body>
<form action="" onsubmit="" method="post">
用户名: <input id="username" name="name" type="text"
placeholder="请输入2-6个字符(字母)"><span
id="span"></span> <br> 密码: <input id="password" name="password"
type="password" placeholder="请输入6个字符(数字字母)"> <br> <input
type="submit" value="注册"> <br>
</form>
</body>
</html>
2.2 post请求
jQuery $.post() 方法
$.post(URL,data,callback);
必需的 URL 参数规定您希望请求的 URL。
可选的 data 参数规定连同请求发送的数据。
可选的 callback 参数是请求成功后所执行的函数名
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript"
src="${pageContext.request.contextPath }/js/jquery-1.4.1.min.js"></script>
<script type="text/javascript">
$(function(){
$("#username").blur(function(){
var username=$("#username").val();
var url="${pageContext.request.contextPath}/check";
$.post(url,{"username":username},function(data,status){
if(status=="success"){
$("#span").html(data);
}
});
})
});
</script>
</head>
<body>
<form action="" onsubmit="" method="post">
用户名: <input id="username" name="name" type="text"
placeholder="请输入2-6个字符(字母)"><span id="span"></span> <br>
密码: <input id="password" name="password" type="password"
placeholder="请输入6个字符(数字字母)"> <br> <input type="submit"
value="注册"> <br>
</form>
</body>
</html>
2.3 ajax方法
ajax() 方法用于执行 AJAX(异步 HTTP)请求。所有的 jQuery AJAX 方法都使用 ajax() 方法。该方法通常用于其他方法不能完成的请求。$.ajax({name:value, name:value, ... })
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript"
src="${pageContext.request.contextPath }/js/jquery-1.4.1.min.js"></script>
<script type="text/javascript">
$(function() {
$("#reg").click(function() {
var username = $("#username").val();
var pwd = $("#password").val();
var sendData = {
"name" : username,
"password" : pwd
};
//contentType: "application/json;charset=utf‐8",
//发送异步请求,并且把数据提交过去
$.ajax({
//需要异步发起的请求
url : "${pageContext.request.contextPath}/register",
//请求需要的数据
data : JSON.stringify(sendData),
//请求的方式
type : "post",
processData : false,//默认是true,是否转换为查询字
//请求结果的数据类型
dataType : "json",
//请求成功后要执行的函数
//data为请求得到的结果
success : function(data) {
if (data.result == "success") {
alert("注册成功");
//location.href = "";
} else {
alert("帐号或密码不合法");
}
},
error : function() {
alert("发生错误");
}
});
});
});
</script>
</head>
<body>
<form action="" onsubmit="" method="post">
用户名: <input id="username" name="name" type="text"
placeholder="请输入2-6个字符(字母)" onblur="checkUserName()"><span
id="span"></span> <br> 密码: <input id="password" name="password"
type="password" placeholder="请输入6个字符(数字字母)"> <br> <input
id="reg" type="button" value="注册"> <br>
</form>
<span id="span1"></span>
</body>
</html>
<wiz_tmp_tag id="wiz-table-range-border" contenteditable="false" style="display: none;">