文章目录
JSON
定义
JSON (JavaScript Object Notation) 是一种轻量级的数据交换格式,易于人阅读和编写。同时也易于机器解析和生成。JSON 采用完全独立于语言的文本格式,而且很多语言都提供了对 json 的支持(包括 C, C++, C#, Java, JavaScript, Perl, Python 等)。 这样就使得 JSON 成为理想的数据交换格式。
json
是一种轻量级的数据交换格式。
轻量级
指的是跟 xml 做比较。
数据交换
指的是客户端
和服务器
之间业务数据的传递格式。
在JavaScript中使用
json的格式
json是由键值对组成,并且由大括号包围。每个键由引号引起来,键与值之间使用冒号进行分隔,多组键值对之间使用逗号进行分隔。
代码演示
<script type="text/javascript">
// json的定义
var jsonObj={
"key1":52,
"key2":"WLM",
"key3":[18,true,"WLM"],
"key4":false,
"key5":{
"key5_1":87,
"key5_2":true
},
"key6":[{
"key6_1":true
},{
"key6_2":666
}]
}
alert(typeof(jsonObj));//json就是一个对象(Object)
</script>
访问json
json 本身是一个对象。
json 中的 key 可以理解为是对象中的一个属性。
json 中的 key 访问就跟访问对象的属性一样: json 对象.key
代码演示
<script type="text/javascript">
// json的访问
alert(jsonObj.key1);
alert(jsonObj.key2);
alert(jsonObj.key3);
for (var i = 0; i < jsonObj.key3.length; i++) {
alert(jsonObj.key3[i]);
}
alert(jsonObj.key5.key5_2);
</script>
两个常用的方法
json 的存在有两种形式。
一种是:对象的形式存在,我们叫它 json 对象。
一种是:字符串的形式存在,我们叫它 json 字符串。
一般在操作 json 中的数据的时候,需要 json 对象的格式。
一般在客户端和服务器之间进行数据交换的时候,使用 json 字符串。
JSON.stringify()
把 json 对象转换成为 json 字符串
JSON.parse()
把 json 字符串转换成为 json 对象
代码演示
<script type="text/javascript">
// json对象转字符串
var jsonObjToString = JSON.stringify(jsonObj);//如同java中的toString()
alert(jsonObjToString)
// json字符串转json对象
var json = JSON.parse(jsonObjToString);
alert(json);
</script>
JSON在Java中使用
先导入需要的jar包:gson-2.2.4.jar https://nowjava.com/jar/detail/m01226855/gson-2.2.4.jar.html
JavaBean和Json的互转
代码演示
@Test
public void test(){
Person person = new Person(11,"WLM");
//创建GSON对象实例
Gson gson = new Gson();
//toJson方法可以把java对象转换成json字符串
String s = gson.toJson(person);
System.out.println(s);
//fromJson将json字符串转换回java对象
Person fromJson = gson.fromJson(s, Person.class);
System.out.println(fromJson);
}
LIst和Json的互转
代码演示
@Test
public void test(){
List<Person> list = new ArrayList<Person>();
list.add(new Person(1,"John"));
list.add(new Person(2,"Merry"));
list.add(new Person(3,"Tom"));
Gson gson = new Gson();
//将list集合转化成json字符串
String s = gson.toJson(list);
System.out.println(s);
//将json字符串转化成list集合
List<Person> persons = gson.fromJson(s, new TypeToken<Person>() {}.getType());
System.out.println(persons);
}
Map和Json的互转
代码演示
@Test
public void test(){
Map<Integer,Person> map = new HashMap<>();
map.put(1, new Person(1,"John"));
map.put(2, new Person(2,"Merry"));
map.put(3, new Person(3,"Tom"));
map.put(4, new Person(4,"Lisa"));
Gson gson = new Gson();
//将map集合转化成json字符串
String s = gson.toJson(map);
System.out.println(s);
//将json字符串转换成map集合
Map<Integer,String> persons = gson.fromJson(s, new TypeToken<HashMap<Integer,Person>>(){}.getType());
System.out.println(persons);
}
AJAX请求
定义
AJAX 即“Asynchronous Javascript And XML”(异步 JavaScript 和 XML),是指一种创建交互式网页应用的网页开发技术。
ajax 是一种浏览器通过 js 异步发起请求,局部更新页面的技术。
Ajax 请求的局部更新(不会舍弃原来页面的内容),浏览器地址栏不会发生变化.
原生JavaScript的Ajax请求
代码演示
AjaxServlet.java
package code;
import com.google.gson.Gson;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @创建人 HeXin
* @所属包 AjaxServlet
* @所属项目 JavaWeb
* @创建时间 2023/2/9 13:51
* @描述 原生JavaScript的ajax请求
*/
public class AjaxServlet extends BaseServlet{
protected void AjaxForJavaScript(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("原生JavaScript的Ajax请求");
Person person = new Person(1,"John");
//json格式字符串
Gson gson = new Gson();
String json = gson.toJson(person);
resp.getWriter().write(json);
}
}
ajax.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="pragma" content="no-cache" />
<meta http-equiv="cache-control" content="no-cache" />
<meta http-equiv="Expires" content="0" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
function ajaxRequest() {
// 1、我们首先要创建XMLHttpRequest
var xmlHttpRequest = new XMLHttpRequest();
// 2、调用open方法设置请求参数
xmlHttpRequest.open("GET","http://localhost:8080/JSON/ajax?action=AjaxForJavaScript",true);
// 2、在send方法前绑定onreadystatechange事件,处理请求完成后的操作。
xmlHttpRequest.onreadystatechange = function() {
if(xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200){
var jsonOnj = JSON.parse(xmlHttpRequest.responseText);
//将响应的数据显示在页面上
document.getElementById("div01").innerHTML = "学号:"+ jsonOnj.id + ",姓名:" + jsonObj.name;
}
}
// 4、调用send方法发送请求
xmlHttpRequest.send();
}
</script>
</head>
<body>
<button onclick="ajaxRequest()">ajax request</button>
<div id="div01">
</div>
</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>AjaxServlet</servlet-name>
<servlet-class>code.AjaxServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>AjaxServlet</servlet-name>
<url-pattern>/ajax</url-pattern>
</servlet-mapping>
</web-app>
jQuery中的Ajax请求
AjaxServlet类中添加如下方法
protected void jQueryAjax(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("jQuery的Ajax请求");
Person person = new Person(1,"Jack");
//json格式字符串
Gson gson = new Gson();
String json = gson.toJson(person);
resp.getWriter().write(json);
}
$.ajax 方法
属性名 | 含义 |
---|---|
url | 表示请求的地址 |
type | 表示请求的类型GET或POST |
data | 表示发给服务器的数据 |
success | 请求成功 |
dataType | 响应的数据类型 |
数据格式有两种:
- name=value&name=value
- {key : value}
常用的数据类型:
text
表示纯文本
xml
表示xml数据
json
表示json对象
代码演示
<script type="text/javascript">
$(function(){
// ajax请求
$("#ajaxBtn").click(function(){
$.ajax({
url:"http://localhost:8080/JSON/ajax",
data:"action=jQueryAjax",
type:"GET",
success : function(data) {
$("#message").html("编号:"+ data.id + " 姓名:" + data.name);
},
dataType : "json"
});
});
</script>
$.get 方法和$.post 方法
属性名 | 含义 |
---|---|
url | 请求的url地址 |
data | 发送数据 |
callback | 成功的回调函数 |
type | 返回的数据类型 |
代码演示
<script type="text/javascript">
// ajax--get请求
$("#getBtn").click(function(){
$.get("http://localhost:8080/JSON/ajax","action=jQueryGet",function(data) {
$("#message").html("jQueryGet的Ajax请求编号:"+ data.id + " 姓名:" + data.name);
},"json");
});
// ajax--post请求
$("#postBtn").click(function(){
// post请求
$.post("http://localhost:8080/JSON/ajax","action=jQueryPost",function(data) {
$("#message").html("jQueryPost的Ajax请求编号:"+ data.id + " 姓名:" + data.name);
},"json");
});
</script>
$.getJSON 方法
属性名 | 含义 |
---|---|
url | 请求的url地址 |
data | 发送给服务器的地址 |
callback | 成功的回调函数 |
代码演示
<script type="text/javascript">
// ajax--getJson请求
$("#getJSONBtn").click(function(){
// 调用
$.getJSON("http://localhost:8080/JSON/ajax","action=jQueryGetJSON",function(data){
$("#message").html("jQueryGetJSON的Ajax请求编号:"+ data.id + " 姓名:" + data.name);
});
});
</script>
表单序列化(serialize)
serialize()可以把表单中所有表单项的内容都获取到,并以name=value&name=value
的形式进行拼接。
代码演示
<script type="text/javascript">
// ajax请求
$("#submit").click(function(){
// 把参数序列化
$.getJSON("http://localhost:8080/JSON/ajax","action=jQuerySerialize&"+$("#form01").serialize(),function(data){
$("#message").html("jQuerySerialize的Ajax请求编号:"+ data.id + " 姓名:" + data.name);
});
});
</script>
完整代码
BaseServlet.java(抽象父类)
package code;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
/**
* @BelongsProject: RentCar4.0
* @BelongsPackage: BaseServlet
* @Author: HeXin
* @CreateTime: 2023/2/3 22:02
* @Description: Servlet抽象父类
* @Version: 1.0
*/
public abstract class BaseServlet extends HttpServlet {
@Override
protected void doGet (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
resp.setContentType("text/html;charset=UTF-8");
String action = req.getParameter("action");
try {
Method method = this.getClass().getDeclaredMethod(action, HttpServletRequest.class, HttpServletResponse.class);
method.invoke(this, req, resp);
}catch (Exception e) {
e.printStackTrace();
}
}
}
AjaxServlet.java
package code;
import com.google.gson.Gson;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @创建人 HeXin
* @所属包 AjaxServlet
* @所属项目 JavaWeb
* @创建时间 2023/2/9 13:51
* @描述 Ajax请求
*/
public class AjaxServlet extends BaseServlet{
protected void AjaxForJavaScript(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("原生JavaScript的Ajax请求");
Person person = new Person(1,"John");
//json格式字符串
Gson gson = new Gson();
String json = gson.toJson(person);
resp.getWriter().write(json);
}
protected void jQueryAjax(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("jQuery的Ajax请求");
Person person = new Person(1,"Jack");
//json格式字符串
Gson gson = new Gson();
String json = gson.toJson(person);
resp.getWriter().write(json);
}
protected void jQueryGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("jQueryGet的Ajax请求");
Person person = new Person(1,"Merry");
//json格式字符串
Gson gson = new Gson();
String json = gson.toJson(person);
resp.getWriter().write(json);
}
protected void jQueryPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("jQueryPost的Ajax请求");
Person person = new Person(1,"Tom");
//json格式字符串
Gson gson = new Gson();
String json = gson.toJson(person);
resp.getWriter().write(json);
}
protected void jQueryGetJSON(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("jQueryGetJSON的Ajax请求");
Person person = new Person(1,"Lisa");
//json格式字符串
Gson gson = new Gson();
String json = gson.toJson(person);
resp.getWriter().write(json);
}
protected void jQuerySerialize(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("jQuerySerialize的Ajax请求");
System.out.println("用户名:"+req.getParameter("username"));
System.out.println("密码:"+req.getParameter("password"));
Person person = new Person(1,"July");
//json格式字符串
Gson gson = new Gson();
String json = gson.toJson(person);
resp.getWriter().write(json);
}
}
AjaxRequest.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="pragma" content="no-cache" />
<meta http-equiv="cache-control" content="no-cache" />
<meta http-equiv="Expires" content="0" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="script/jquery-1.7.2.js"></script>
<script type="text/javascript">
$(function(){
// ajax请求
$("#ajaxBtn").click(function(){
$.ajax({
url:"http://localhost:8080/JSON/ajax",
data:"action=jQueryAjax",
type:"GET",
success : function(data) {
$("#message").html("编号:"+ data.id + " 姓名:" + data.name);
},
dataType : "json"
});
});
// ajax--get请求
$("#getBtn").click(function(){
$.get("http://localhost:8080/JSON/ajax","action=jQueryGet",function(data) {
$("#message").html("jQueryGet的Ajax请求编号:"+ data.id + " 姓名:" + data.name);
},"json");
});
// ajax--post请求
$("#postBtn").click(function(){
// post请求
$.post("http://localhost:8080/JSON/ajax","action=jQueryPost",function(data) {
$("#message").html("jQueryPost的Ajax请求编号:"+ data.id + " 姓名:" + data.name);
},"json");
});
// ajax--getJson请求
$("#getJSONBtn").click(function(){
// 调用
$.getJSON("http://localhost:8080/JSON/ajax","action=jQueryGetJSON",function(data){
$("#message").html("jQueryGetJSON的Ajax请求编号:"+ data.id + " 姓名:" + data.name);
});
});
// ajax请求
$("#submit").click(function(){
// 把参数序列化
$.getJSON("http://localhost:8080/JSON/ajax","action=jQuerySerialize&"+$("#form01").serialize(),function(data){
$("#message").html("jQuerySerialize的Ajax请求编号:"+ data.id + " 姓名:" + data.name);
});
});
});
</script>
</head>
<body>
<div>
<button id="ajaxBtn">$.ajax请求</button>
<button id="getBtn">$.get请求</button>
<button id="postBtn">$.post请求</button>
<button id="getJSONBtn">$.getJSON请求</button>
</div>
<div id="message">
</div>
<br/><br/>
<form id="form01" >
用户名:<input name="username" type="text" /><br/>
密码:<input name="password" type="password" /><br/>
下拉单选:<select name="single">
<option value="Single">Single</option>
<option value="Single2">Single2</option>
</select><br/>
下拉多选:
<select name="multiple" multiple="multiple">
<option selected="selected" value="Multiple">Multiple</option>
<option value="Multiple2">Multiple2</option>
<option selected="selected" value="Multiple3">Multiple3</option>
</select><br/>
复选:
<input type="checkbox" name="check" value="check1"/> check1
<input type="checkbox" name="check" value="check2" checked="checked"/> check2<br/>
单选:
<input type="radio" name="radio" value="radio1" checked="checked"/> radio1
<input type="radio" name="radio" value="radio2"/> radio2<br/>
</form>
<button id="submit">提交--serialize()</button>
</body>
</html>