通过在后台与服务器进行少量数据交换,Ajax可以使页面进行异步更新,即无需加载整个页面的情况下,进行局部更新
XmlHttpRequest对象,ajax技术就是使用该对象通过http协议在浏览器和服务器之间收发xml或其他数据,与服务器进行异步交互使页面局部刷新,是ajax的核心对象。
使用步骤
- 创建XMLHttpRequest对象
var xhr=new XMLHttpRequest();
- 给定请求方式以及请求地址
xhr.open("get","http://www.xiaomi.com");
- 发送请求
xhr.send();
- 获取服务器给客户端的响应数据
//该函数是一种回调,当send执行完后立即调用该函数
xhr.onreadystatechange=function(){
//0:open()没有被调用
//1:open()正在被调用
//2:send()正在被调用
//3:服务端正在返回结果
//4:请求结束,数据已经从服务端发送到客户端
if(xhr.readystate == 4 && xhr.status == 200){
//数据处理 xhr.responseText表示响应信息
alert(xhr.responseText);
}
}
使用demo
jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Ajax</title>
<script>
function but() {
var xhr=new XMLHttpRequest();
xhr.open("get","ajax.do");
xhr.send();
xhr.onreadystatechange=function () {
if(xhr.readyState==4&&xhr.status==200){
document.getElementById("span").innerHTML=xhr.responseText;
}
}
}
</script>
</head>
<body>
<h2>Ajax学习</h2>
<span id="span"></span>
<input type="button" typeof="button" value="OK" onclick="but()">
</body>
</html>
servlet
@WebServlet("/ajax.do")
public class AjaxServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
PrintWriter pw=resp.getWriter();
pw.println("Hello Ajax");
pw.flush();
pw.close();
}
}
Json
Json格式
在Json没有出现之前Ajax中的数据传递是用的xml,Json比xml更小,更容易解析
- 大括号表示Json对象 {}
- 属性和值用冒号分隔 “key”:“value”
- 属性和属性之间用逗号分隔 {“key”:“value”,“key”:“value”}
- 数组最外边用中括号括起来,每个对象用大括号表示对象 [{“key”:“value”},{“key”:“value”}]
Jackson
因为JDK中并不支持json格式,所以需要导入Json解析类库,谷歌的Gson,阿里的FastJson,Jackson,springmvc中默认使用Jackson处理Json格式的数据
Jackson -annotations
Jackson -core
Jackson -databind
- 通过Jackson API将Java对象转换成Json格式
- 修改响应头,类型为 application/json
- 将结果用字符流推给浏览器
- 页面中通过JSON.parse()将数据转换成JS对象
Jackson demo
pojo
public class Users {
private int id;
private String username;
public Users() {
}
public Users(int id, String username) {
this.id = id;
this.username = username;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
package cn.wit;
import cn.wit.pojo.Users;
import com.fasterxml.jackson.databind.ObjectMapper;
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 java.io.IOException;
import java.io.PrintWriter;
@WebServlet("/ajax.do")
public class AjaxServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Users users=new Users();
users.setId(1);
users.setUsername("张三");
//使用Jackson API将Java对象转换成Json对象
//ObjectMapper是 Jackson的核心类
ObjectMapper objectMapper=new ObjectMapper();
String usersStr=objectMapper.writeValueAsString(users);
//解决中文乱码问题
//响应编码设置 用内容json 格式utf-8 解析我的数据
resp.setContentType("text/json; charset=utf-8");
//请求编码设置 发给我utf-8格式
resp.setCharacterEncoding("utf-8");
PrintWriter pw=resp.getWriter();
pw.print(usersStr);
pw.flush();
pw.close();
}
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Ajax</title>
<script>
function but() {
var xhr=new XMLHttpRequest();
xhr.open("get","ajax.do");
xhr.send();
xhr.onreadystatechange=function () {
if(xhr.readyState==4&&xhr.status==200){
var users=JSON.parse(xhr.responseText);
document.getElementById("span").innerHTML=users.id+":"+users.username;
}
}
}
</script>
</head>
<body>
<h2>Ajax学习</h2>
<span id="span"></span>
<br/>
<input type="button" typeof="button" value="OK" onclick="but()">
</body>
</html>
通过jackson也可以传递List、Map(没有模板时可以使用map)等对象,不再详述
json格式请求
Jackson -annotations
Jackson -core
Jackson -databind
json格式请求必须传递js对象
通过JSON.stringify()将js对象转换成json格式
请求方式必须为post
通过send方式将数据推到服务器
服务端通过输入流拿到数据,再通过jackson的API解析json格式的数据流转为java对象
json请求demo
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Ajax</title>
<script>
function but() {
var xhr=new XMLHttpRequest();
xhr.open("post","ajax.do");
var username=document.getElementById("username").value;
var password=document.getElementById("password").value;
//这里属性名称必须要与转换的java对象属性名完全一致
var obj={username:username,password:password};
var content=JSON.stringify(obj);
xhr.send(content);
xhr.onreadystatechange=function () {
if(xhr.readyState==4&&xhr.status==200){
var ok=xhr.responseText;
document.getElementById("span").innerHTML=ok;
}
}
}
</script>
</head>
<body>
<h2>Ajax学习</h2>
账号:<input type="text" name="username" id="username"> <br/>
密码:<input type="text" name="password" id="password"><br/>
<input type="button" typeof="button" value="OK" onclick="but()">
<span id="span"></span>
</body>
</html>
package cn.wit;
import cn.wit.pojo.Users;
import com.fasterxml.jackson.databind.ObjectMapper;
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 java.io.IOException;
import java.io.PrintWriter;
@WebServlet("/ajax.do")
public class AjaxServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//从请求体中获取请求数据
String s = req.getReader().readLine();
//使用Jackson将json对象转换为java对象
ObjectMapper objectMapper=new ObjectMapper();
Users users = objectMapper.readValue(s, Users.class);
System.out.println(users.getUsername()+":"+users.getPassword());
PrintWriter printWriter=resp.getWriter();
printWriter.write("OK");
printWriter.flush();
printWriter.close();
}
}
public class Users {
private String username;
private String password;
public Users(String username, String password) {
this.username = username;
this.password = password;
}
public Users() {
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
Jackson注解
JQuery的ajax使用
在JQuery中提供了对ajax的封装,使得ajax步骤更加简单
$.ajax() 基本demo
$.ajax({key:value,key:value})
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Ajax</title>
<script src="js/jquery-1.7.2.js"></script>
<script>
function but() {
$.ajax({
type:"get",
url:"ajax.do",
success:function (result) {
$("#span").html(result);
}
});
}
</script>
</head>
<body>
<h2>Ajax学习</h2>
<span id="span"></span>
<input type="button" typeof="button" value="OK" onclick="but()"><br/>
</body>
</html>
@WebServlet("/ajax.do")
public class AjaxServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
PrintWriter printWriter=resp.getWriter();
printWriter.print("Jquery Ajax");
printWriter.flush();
printWriter.close();
}
}
$.ajax() 普通传递
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Ajax</title>
<script src="js/jquery-1.7.2.js"></script>
<script>
function but() {
var username=$("#username").val();
var password=$("#password").val();
$.ajax({
type:"get",
url:"ajax.do",
data:"username="+username+"&password="+password,
success:function (result) {
$("#span").html(result);
}
});
}
</script>
</head>
<body>
<h2>Ajax学习</h2>
账号:<input type="text" name="username" id="username"> <br/>
密码:<input type="text" name="password" id="password"><br/>
<input type="button" typeof="button" value="OK" onclick="but()">
</body>
</html>
@WebServlet("/ajax.do")
public class AjaxServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取数据
String username=req.getParameter("username");
String password=req.getParameter("password");
System.out.println(username+":"+password);
}
}
$.ajax() js对象传递
同普通传递,仅仅改变data格式,同样用request.getParameter方式获取
$.ajax({
type:"get",
url:"ajax.do",
data: {
username:username,
password:password
},
success:function (result) {
$("#span").html(result);
}
});
$.ajax() json格式传递
同上边相比仅改变data
data: JSON.stringify({
username:username,
password:password
}),
@WebServlet("/ajax.do")
public class AjaxServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//从请求体中获取请求数据
String s = req.getReader().readLine();
//使用Jackson将json对象转换为java对象
ObjectMapper objectMapper=new ObjectMapper();
Users users = objectMapper.readValue(s, Users.class);
System.out.println(users.getUsername()+":"+users.getPassword());
}
}
springmvc中的ajax
该文章最后一个章节讲解了ajax技术在springmvc中的使用步骤