JSON&AJAX 请求

本文详细介绍了JSON,包括其在JavaScript和Java中的使用,以及JSON对象与字符串的转换方法。接着阐述了AJAX的基本概念,展示了原生JavaScript和jQuery中AJAX请求的示例,强调了其异步特性和局部更新页面的能力。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、什么是 JSON

JSON (JavaScript Object Notation) 是⼀种轻量级的数据交换格式。易于⼈阅读和编写。同时也易于机
器解析和⽣成。JSON
采⽤完全独⽴于语⾔的⽂本格式,⽽且很多语⾔都提供了对 json 的⽀持(包括 C, C++, C#, Java,JavaScript, Perl, Python
等)。 这样就使得 JSON 成为理想的数据交换格式。

     json 是⼀种轻量级的数据交换格式。


     轻量级指的是跟 xml 做⽐较。


    数据交换指的是客户端和服务器之间业务数据的传递格式。

 

1.1、JSON 在 JavaScript 中的使⽤

1.1.1、json 的定义
 

json 是由键值对组成,并且由花括号(⼤括号)包围。每个键由引号引起来,键和值之间使⽤冒号进⾏
分隔,
多组键值对之间使⽤逗号进⾏分隔。

<!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">
			// json的定义
			var Json={
				"key1":"xixi",
				"key2":200,
				"key3":["xixi",2000,true],
				"key4":{
					"key4_1":"ti",
					"key4_2":"ti2"
				},
				"key5":[{
					"key5_1_1":"ti5_11"
				},{
					"key5_1_2":"ti5_12"
				}]

			};
			// json的访问
			// alert(Json.key1);
			// alert(Json.key3);
			// alert(Json.key4.key4_1)
			var json=Json.key5[0];
				// alert(json.key5_1_1);
			// json对象转字符串
			var jsonString=JSON.stringify(Json);
			// alert(jsonString)
			// json字符串转json对象
			alert(JSON.parse(jsonString))
		</script>
	</head>
	<body>
		
	</body>
</html>

1.1.2、json 的访问

json 本身是⼀个对象。
json 中的 key 我们可以理解为是对象中的⼀个属性。
json 中的 key 访问就跟访问对象的属性⼀样: json 对象.key

<!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">
			// json的定义
			var Json={
				"key1":"xixi",
				"key2":200,
				"key3":["xixi",2000,true],
				"key4":{
					"key4_1":"ti",
					"key4_2":"ti2"
				},
				"key5":[{
					"key5_1_1":"ti5_11"
				},{
					"key5_1_2":"ti5_12"
				}]

			};
			//json的访问
			alert(Json.key1);
			alert(Json.key3);
			alert(Json.key4.key4_1)
			var json=Json.key5[0];
				alert(json.key5_1_1);
			//json对象转字符串
			var jsonString=JSON.stringify(Json);
			alert(jsonString)
			json字符串转json对象
			alert(JSON.parse(jsonString))
		</script>
	</head>
	<body>
		
	</body>
</html>

1.1.3、json 的两个常⽤⽅法

json 的存在有两种形式:
⼀种是:对象的形式存在,我们叫它 json 对象。
⼀种是:字符串的形式存在,我们叫它 json 字符串。


⼀般我们要操作 json 中的数据的时候,需要 json 对象的格式。
⼀般我们要在客户端和服务器之间进⾏数据交换的时候,使⽤ json 字符串。


JSON.stringify() 把 json 对象转换成为 json 字符串
JSON.parse() 把 json 字符串转换成为 json 对象

<!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">
			// json的定义
			var Json={
				"key1":"xixi",
				"key2":200,
				"key3":["xixi",2000,true],
				"key4":{
					"key4_1":"ti",
					"key4_2":"ti2"
				},
				"key5":[{
					"key5_1_1":"ti5_11"
				},{
					"key5_1_2":"ti5_12"
				}]

			};
			//json的访问
			alert(Json.key1);
			alert(Json.key3);
			alert(Json.key4.key4_1)
			var json=Json.key5[0];
				alert(json.key5_1_1);
			//json对象转字符串
			var jsonString=JSON.stringify(Json);
			alert(jsonString)
			json字符串转json对象
			alert(JSON.parse(jsonString))
		</script>
	</head>
	<body>
		
	</body>
</html>

1.2、JSON 在 java 中的使⽤
 

1.2.1、javaBean 和 json 的互转

1.导⼊⾕歌的 gson 包:gson-2.2.4.jar
2.新建 JavaBean

package com.dd.pojo;

public class User {
    private Integer id;
    private String name;

    public User() {
    }

    public User(Integer id, String name) {
        this.id = id;
        this.name = name;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}

3.测试类:

1.2.2、List 和 json 的互转

package com.dd.test;

import com.dd.pojo.User;
import com.dd.pojo.UserListType;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;

public class Test {
        public static void main(String[] args) {
                User user=new User(1,"小东东");
                //将 JavaBean 转换为 JSON 字符串
                Gson gson=new Gson();
                String toJsonUser = gson.toJson(user);
                System.out.println(toJsonUser);
                //将 JSON 字符串转换为 JavaBean
                User user2 = gson.fromJson(toJsonUser, User.class);
                System.out.println(user2);


        }
        @org.junit.Test
        public void test(){
                List<User> userList=new ArrayList<User>();
                User user1=new User(1,"小东东");
                User user2=new User(2,"大东东");


                userList.add(user1);
                userList.add(user2);

                Gson gson=new Gson();
                //对象数据转为  JSON 数组
                String toJsonUserString = gson.toJson(userList);
                System.out.println(toJsonUserString);

                //JSON数组 转为对象
                Object o = gson.fromJson(toJsonUserString, new UserListType().getType());
                System.out.println(o);

        }


}

List JSON 数组 转为对象的时候所使用的方法时不同的,不然将会转为失败:

要解决上面的问题:要使用不同方法:

1.

2.还要写一个类继承TypeToken,里面啥也不用写

TypeToken<>尖括号写的类型要调用写的一致

 发现上面写这种调用的方法不同类型的都要写一个类,感觉要写很多的类 ,其实可以使用内部类来解决这个问题的。

1.2.3、map 和 json 的互转

以上是使用内部类的,就不要那么麻烦去写一个类的,可以节约很多的时间。

2、AJAX 请求

2.1、什么是 AJAX 请求

AJAX 即“Asynchronous Javascript And XML”(异步 JavaScript 和 XML),是指⼀种创建交互式⽹⻚应
⽤的⽹⻚开发 技术。
ajax 是⼀种浏览器通过 js 异步发起请求,局部更新⻚⾯的技术。
Ajax 请求的局部更新,浏览器地址栏不会发⽣变化
局部更新不会舍弃原来⻚⾯的内容

2.2、原⽣ AJAX 请求的示例

 

<!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/ajaxServlet?action=javaScriptAjaxServlet",true);

				//4、在send方法前绑定onreadystatechange事件,处理请求完成后的操作。
				xmlHttpRequest.onreadystatechange = function () {
					if(xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200){
						alert(xmlHttpRequest.responseText);
					}
				}
// 				3、调用send方法发送请求
				xmlHttpRequest.send();
			}
		</script>
	</head>
	<body>
		<a href="http://localhost:8080/json/ajaxServlet?action=javaScriptAjaxServlet">请求</a>
		<button onclick="ajaxRequest()">ajax request</button>
		<div id="div01">
		</div>
		<br>
		<br>
		<table border="1">
			<tr>
				<td>1.1</td>
				<td>1.2</td>
			</tr>
			<tr>
				<td>2.1</td>
				<td>2.2</td>
			</tr>
		</table>
	</body>
</html>

2.3、jQuery 中的 AJAX 请求

$.ajax ⽅法
url 表示请求的地址
type 表示请求的类型 GET 或 POST 请求
data 表示发送给服务器的数据
格式有两种:
⼀:name=value&name=value

⼆:{key:value}
success 请求成功,响应的回调函数
dataType 响应的数据类型
常⽤的数据类型有:
text 表示纯⽂本
xml 表示 xml 数据
json 表示 json 对象

// ajax请求
				$("#ajaxBtn").click(function(){
					
					$.ajax({
						url:"http://localhost:8080/json/ajaxServlet",
						type:"GET",
						data:"action=jQueryAjaxServlet",
						success:function (data) {
							$("#msg").html("编号:" + data.id + ", 姓名:" + data.name);
							// alert(data)
						},
						dataType:"json"
					})

				});

$.get ⽅法和$.post ⽅法
url 请求的 url 地址
data 发送的数据
callback 成功的回调函数
type 返回的数据类型

// ajax--get请求
				$("#getBtn").click(function(){

					$.get("http://localhost:8080/json/ajaxServlet","action=jQueryGet",function (data) {
						$("#msg").html("Get 编号:" + data.id + ", 姓名:" + data.name);
					},"json");
					
				});
				
				// ajax--post请求
				$("#postBtn").click(function(){
					// post请求
					$.post("http://localhost:8080/json/ajaxServlet","action=jQueryPost",function (data) {
						$("#msg").html("Post 编号:" + data.id + ", 姓名:" + data.name);
					},"json");
					
				});

$.getJSON ⽅法
url 请求的 url 地址
data 发送给服务器的数据
callback 成功的回调函数

// ajax--getJson请求
				$("#getJSONBtn").click(function(){
					// 调用
					$.getJSON("http://localhost:8080/json/ajaxServlet","action=jQueryGetJSON",function (data) {
						$("#msg").html("jQueryGetJSON 编号:" + data.id + ", 姓名:" + data.name);
					});

				});

表单序列化 serialize()
serialize()可以把表单中所有表单项的内容都获取到,并以 name=value&name=value 的形式进⾏拼
接。

// ajax请求
				$("#submit").click(function(){
					// 把参数序列化

					alert($("#form01").serialize());

					$.getJSON("http://localhost:8080/json/ajaxServlet","action=jQuerySerialize",function (data) {
						$("#msg").html("jQuerySerialize 编号:" + data.id + ", 姓名:" + data.name);
					});
				});

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值