【Ajax】
Asynchronous JavaScript and XML(异步的 JavaScript 和 XML)
JavaScript:可以动态修改页面。
1. 异步和同步的概念
同步现象:客户端发送请求到服务器端, 在服务器返回响应之前, 客户端都处于等待卡死状态
异步现象:客户端发送请求到服务器端, 无论服务器是否返回响应, 客户端都可以随时的做其他事情, 不会被卡死
2. 使用AJAX
js原生ajax
get发送异步请求,get发送同步请求,post发送异步请求比较:
<%@ 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">
<title>Insert title here</title>
</head>
<body>
<!-- js原生Ajax -->
<input type="button" value="get发送异步请求" onclick="fn1()">
<input type="button" value="get发送同步请求" onclick="fn2()">
<input type="button" value="post发送异步请求" onclick="fn3()">
<script type="text/javascript">
function fn1(){
// 1. 创建异步传输对象
var xmlhttp = new XMLHttpRequest();
// 2. 设置好响应回来的时候要触发的函数
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
// 4. 接收服务器的响应
var res = xmlhttp.responseText;
alert(res);
}
}
// 3. 发送Ajax请求
xmlhttp.open("GET","/Ajax/s2?name=李四",true);
xmlhttp.send();
}
function fn2(){
// 1. 创建异步传输对象
var xmlhttp = new XMLHttpRequest();
// 2. 设置好响应回来的时候要触发的函数
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
// 4. 接收服务器的响应
var res = xmlhttp.responseText;
alert(res);
}
}
// 3. 发送Ajax请求
xmlhttp.open("GET","/Ajax/s2", false);
xmlhttp.send();
}
function fn3(){
// 1. 创建异步传输对象
var xmlhttp = new XMLHttpRequest();
// 2. 设置好响应回来的时候要触发的函数
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
// 4. 接收服务器的响应
var res = xmlhttp.responseText;
alert(res);
}
}
// 3. 发送Ajax请求
xmlhttp.open("POST","/Ajax/s2",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("name=李四");
}
</script>
</body>
</html>
实现云计算:
<%@ 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">
<title>Insert title here</title>
</head>
<body>
<input id="num1" type="text" name="num1"><br />
+ <br />
<input id="num2" type="text" name="num2"><br />
<input id="btn_cal" type="button" value="=" onclick="cal()"> <br />
<div id="div_res">结果</div>
<script type="text/javascript">
function cal(){
// 先取出num1和num2的值
var num1 = document.getElementById("num1").value;
var num2 = document.getElementById("num2").value;
// 1. 创建异步传输对象
var xmlhttp = new XMLHttpRequest();
// 2. 设置好响应回来的时候要触发的函数
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
// 4. 接收服务器的响应
var res = xmlhttp.responseText;
// 把结果显示在页面上
document.getElementById("div_res").innerHTML = res;
}
}
// 3. 发送Ajax请求
var url = "/Ajax/s3?num1=" + num1 +"&num2="+num2
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
</script>
</body>
</html>
对应的servlet就不贴了,里面的代码功能就是获取num1和num2参数,相加,发送给浏览器
jquery封装了ajax的方法
get请求,post请求,ajax请求:
<%@ 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">
<title>Insert title here</title>
</head>
<body>
<input id="btn1" type="button" value="get请求">
<input id="btn2" type="button" value="post请求">
<input id="btn3" type="button" value="ajax请求">
<script type="text/javascript" src="/Ajax/js/jquery-1.7.2.js"></script>
<script type="text/javascript">
$(function() {
$("#btn1").click(function() {
$.get("/Ajax/s4", {
name : "John",
time : "2pm"
}, function(data) {
alert(data.name);
}, "json");
})
$("#btn2").click(function() {
$.post("/Ajax/s4", {
name : "John",
time : "2pm"
}, function(data) {
alert(data.name);
}, "json");
})
$("#btn3").click(function() {
$.ajax({
type : "GET",
url : "/Ajax/s4",
data : "name=John&time=Boston",
success : function(msg) {
alert(msg.height);
},
statusCode : {
404 : function() {
alert('欢迎来到火星!');
},
500 : function(){
alert('服务器出错!')
}
},
dataType : "json"
});
})
})
</script>
</body>
</html>
【JSON】
java后端和前端交互最优先的数据格式就是json,因为json格式可以是很复杂的数据类型
其本质就是js中的对象
"key":"value" , "key":"value"格式
{} 表示一个对象
java中写一个类
class Person{
String name;
int age;
}
new Person("abc", 18);
如果用json写
{"name":"abc", "age":"18"}
[] 表示一个数组
<%--
json数组
[{"name":"张三", "age":"18"},
{"name":"李四", "age":"21"}]
--%>
<script type="text/javascript">
var arr = [{"name":"张三", "age":"18"},
{"name":"李四", "age":"21"}];
// 打印张三
alert(arr[0].name);
//21
alert(arr[1].age);
复杂json对象
<script type="text/javascript">
var json = {
"key0":"李四",
"key1": {"name":"张三", "age":"18"},
"key2":[
{"name":"王五", "age":"18"},
{"name":"赵六", "age":"26"},
{"name":"田七", "age":"27"}
]
};
// 李四
alert(json.key0);
// 张三
alert(json.key1.name);
// 田七
alert(json.key2[2].name);
</script>
服务器如何把javabean,map类型等转化成json格式对象?
在这里用到了一个jar包gson.jar,由谷歌公司开发。
// 发送一个学生对象给客户端, 姓名 年龄 身高
Map<String, String> map = new HashMap<>();
map.put("name", "张三");
map.put("age", "18");
map.put("height", "196");
// 转成json
String json = new Gson().toJson(map);
response.getWriter().write(json);
检测用户名是否可以使用功能改进(采用json格式传递数据)
package com.bwf.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.bwf.service.UserService;
import com.bwf.service.impl.UserServiceImpl;
public class CheckUnameServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private UserService us = new UserServiceImpl();
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html; charset=UTF-8");
// 接收用户请求
String uname = request.getParameter("uname");
System.out.println(uname);
// 调用业务逻辑层判断uname是否存在
boolean exists = us.checkUname(uname);
// true
// exists:true , content:用户名已存在
String content = exists ? "用户名已存在" : "用户名可以使用!";
// exists:true , content:用户名已存在
//{"exists":true, "content":"用户名已存在"}
String json = "{\"exists\":"+ exists +", \"content\":\"" + content +"\"}";
// 返回结果给客户端
response.getWriter().write(json);
}
}
如果服务器返回json格式的字符串给客户端,那么如何转换成json对象呢?
function check(){
var uname = document.getElementById("uname").value;
// 1. 创建异步传输对象
var xmlhttp = new XMLHttpRequest();
// 2. 设置好响应回来的时候要触发的函数
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
// 4. 接收服务器的响应
//拿到的是String类型
var res = xmlhttp.responseText;
// exists:true , content:用户名已存在
//{"exists":true, "content":"用户名已存在"}
//String转json方法1
var json = eval('(' + res + ')');
//String转json方法2
//var json = JSON.parse(res);
// 根据结果显示对应的内容
var span = document.getElementById("span1");
span.innerHTML = json.content;
if(json.exists){
span.style.color = "red";
}else{
span.style.color = "green";
}
}
}
// 3. 发送Ajax请求
xmlhttp.open("GET","/Servlet02/check?uname=" + uname,true);
xmlhttp.send();