Ajax 是一种在无需重新加载整个网页的情况下,能够更新部分网页的技术。
通过在后台与服务器进行少量数据交换,Ajax 可以使网页实现异步更新。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。
传统的网页(不使用 Ajax)如果需要更新内容,必须重载整个网页页面。
提升用户的体验
//1.创建核心对象
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
//2. 建立连接
/*
参数:
1. 请求方式:GET、POST
* get方式,请求参数在URL后边拼接。send方法为空参
* post方式,请求参数在send方法中定义
2. 请求的URL:
3. 同步或异步请求:true(异步)或 false(同步)
*/
xmlhttp.open("GET","ajaxServlet?username=tom",true);
//3.发送请求
xmlhttp.send();
//4.接受并处理来自服务器的响应结果
//获取方式 :xmlhttp.responseText
//什么时候获取?当服务器响应成功后再获取
//当xmlhttp对象的就绪状态改变时,触发事件onreadystatechange。
xmlhttp.onreadystatechange=function()
{
//判断readyState就绪状态是否为4,判断status响应状态码是否为200
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
//获取服务器的响应结果
var responseText = xmlhttp.responseText;
alert(responseText);
}
}
$.ajax()
$.ajax({
url:"ajaxServlet1111" , // 请求路径
type:"POST" , //请求方式
//data: "username=jack&age=23",//请求参数
data:{"username":"jack","age":23},
success:function (data) {
alert(data);
},//响应成功后的回调函数
error:function () {
alert("出错啦...")
},//表示如果请求响应出现错误,会执行的回调函数
dataType:"text"//设置接受到的响应数据的格式
});
$.get():发送get请求
$.post():发送post请求
Java格式
Person p = new Person();
p.setName("张三");
p.setAge(23);
p.setGender("男");
JSON格式
var p = {"name":"张三","age":23,"gender":"男"};
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
<script>
//1.定义基本格式
var person = {"name": "张三", age: 23, 'gender': true};
//获取name的值
//var name = person.name;
var name = person["name"];
// alert(name);
//alert(person);
//2.嵌套格式 {}———> []
var persons = {
"persons": [
{"name": "张三", "age": 23, "gender": true},
{"name": "李四", "age": 24, "gender": true},
{"name": "王五", "age": 25, "gender": false}
]
};
// alert(persons);
//获取王五值
var name1 = persons.persons[2].name;
// alert(name1);
//2.嵌套格式 []———> {}
var ps = [{"name": "张三", "age": 23, "gender": true},
{"name": "李四", "age": 24, "gender": true},
{"name": "王五", "age": 25, "gender": false}];
//获取李四值
//alert(ps);
alert(ps[1].name);
script>
head>
<body>
body>
html>
//1.定义基本格式
var person = {"name": "张三", age: 23, 'gender': true};
var ps = [{"name": "张三", "age": 23, "gender": true},
{"name": "李四", "age": 24, "gender": true},
{"name": "王五", "age": 25, "gender": false}];
//获取person对象中所有的键和值
//for in 循环
/* for(var key in person){
//这样的方式获取不行。因为相当于 person."name"
//alert(key + ":" + person.key);
alert(key+":"+person[key]);
}*/
//获取ps中的所有值
for (var i = 0; i < ps.length; i++) {
var p = ps[i];
for(var key in p){
alert(key+":"+p[key]);
}
}
JSON解析器: 常见的解析器:Jsonlib,Gson,fastjson,jackson
//演示 JSON字符串转为Java对象
@Test
public void test5() throws Exception {
//1.初始化JSON字符串
String json = "{\"gender\":\"男\",\"name\":\"张三\",\"age\":23}";
//2.创建ObjectMapper对象
ObjectMapper mapper = new ObjectMapper();
//3.转换为Java对象 Person对象
Person person = mapper.readValue(json, Person.class);
System.out.println(person);
}
}
使用步骤:
转换方法:
注解:
复杂java对象转换
package cn.itcast.test;
import cn.itcast.domain.Person;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
import java.io.FileWriter;
import java.util.*;
public class JacksonTest {
//Java对象转为JSON字符串
@Test
public void test1() throws Exception {
//1.创建Person对象
Person p = new Person();
p.setName("张三");
p.setAge(23);
p.setGender("男");
//2.创建Jackson的核心对象 ObjectMapper
ObjectMapper mapper = new ObjectMapper();
//3.转换
/*
转换方法:
writeValue(参数1,obj):
参数1:
File:将obj对象转换为JSON字符串,并保存到指定的文件中
Writer:将obj对象转换为JSON字符串,并将json数据填充到字符输出流中
OutputStream:将obj对象转换为JSON字符串,并将json数据填充到字节输出流中
writeValueAsString(obj):将对象转为json字符串
*/
String json = mapper.writeValueAsString(p);
//{"name":"张三","age":23,"gender":"男"}
//System.out.println(json);//{"name":"张三","age":23,"gender":"男"}
//writeValue,将数据写到d://a.txt文件中
//mapper.writeValue(new File("d://a.txt"),p);
//writeValue.将数据关联到Writer中
mapper.writeValue(new FileWriter("d://b.txt"),p);
}
@Test
public void test2() throws Exception {
//1.创建Person对象
Person p = new Person();
p.setName("张三");
p.setAge(23);
p.setGender("男");
p.setBirthday(new Date());
//2.转换
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(p);
System.out.println(json);//{"name":"张三","age":23,"gender":"男","birthday":1530958029263}
//{"name":"张三","age":23,"gender":"男","birthday":"2018-07-07"}
}
@Test
public void test3() throws Exception {
//1.创建Person对象
Person p = new Person();
p.setName("张三");
p.setAge(23);
p.setGender("男");
p.setBirthday(new Date());
Person p1 = new Person();
p1.setName("张三");
p1.setAge(23);
p1.setGender("男");
p1.setBirthday(new Date());
Person p2 = new Person();
p2.setName("张三");
p2.setAge(23);
p2.setGender("男");
p2.setBirthday(new Date());
//创建List集合
List<Person> ps = new ArrayList<Person>();
ps.add(p);
ps.add(p1);
ps.add(p2);
//2.转换
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(ps);
// [{},{},{}]
//[{"name":"张三","age":23,"gender":"男","birthday":"2018-07-07"},{"name":"张三","age":23,"gender":"男","birthday":"2018-07-07"},{"name":"张三","age":23,"gender":"男","birthday":"2018-07-07"}]
System.out.println(json);
}
@Test
public void test4() throws Exception {
//1.创建map对象
Map<String,Object> map = new HashMap<String,Object>();
map.put("name","张三");
map.put("age",23);
map.put("gender","男");
//2.转换
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(map);
//{"name":"张三","age":23,"gender":"男"}
System.out.println(json);//{"gender":"男","name":"张三","age":23}
}
校验用户名是否存在
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>注册页面title>
<script src="js/jquery-3.3.1.min.js">script>
<script>
//在页面加载完成后
$(function () {
//给username绑定blur事件
$("#username").blur(function () {
//获取username文本输入框的值
var username = $(this).val();
//发送ajax请求
//期望服务器响应回的数据格式:{"userExsit":true,"msg":"此用户名太受欢迎,请更换一个"}
// {"userExsit":false,"msg":"用户名可用"}
$.get("findUserServlet",{username:username},function (data) {
//判断userExsit键的值是否是true
// alert(data);
var span = $("#s_username");
if(data.userExsit){
//用户名存在
span.css("color","red");
span.html(data.msg);
}else{
//用户名不存在
span.css("color","green");
span.html(data.msg);
}
});
});
});
script>
head>
<body>
<form>
<input type="text" id="username" name="username" placeholder="请输入用户名">
<span id="s_username">span>
<br>
<input type="password" name="password" placeholder="请输入密码"><br>
<input type="submit" value="注册"><br>
form>
body>
html>
FindUserServlet
package cn.itcast.web.servlet;
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.util.HashMap;
import java.util.Map;
@WebServlet("/findUserServlet")
public class FindUserServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.获取用户名
String username = request.getParameter("username");
//2.调用service层判断用户名是否存在
//期望服务器响应回的数据格式:{"userExsit":true,"msg":"此用户名太受欢迎,请更换一个"}
// {"userExsit":false,"msg":"用户名可用"}
//设置响应的数据格式为json
response.setContentType("application/json;charset=utf-8");
Map<String,Object> map = new HashMap<String,Object>();
if("tom".equals(username)){
//存在
map.put("userExsit",true);
map.put("msg","此用户名太受欢迎,请更换一个");
}else{
//不存在
map.put("userExsit",false);
map.put("msg","用户名可用");
}
//将map转为json,并且传递给客户端
//将map转为json
ObjectMapper mapper = new ObjectMapper();
//并且传递给客户端
mapper.writeValue(response.getWriter(),map);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}