Ajax即Asynchronous Javascript And XML(异步JavaScript和XML)在 2005年被Jesse James Garrett提出的新术语,用来描述一种使用现有技术集合的‘新’方法,包括: 或 XHTML, CSS, JavaScript, DOM, XML, XSLT, 以及最重要的XMLHttpRequest。 [3] 使用Ajax技术网页应用能够快速地将增量更新呈现在用户界面上,而不需要重载(刷新)整个页面,这使得程序能够更快地回应用户的操作。 [3]
jQuery AJAX API
$.ajax({
url: "",
type: "",
data: {
name: "yhc",
id: 5321
},
success: function(res) {
console.log(res)
}
})
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2022/8/20 0020
Time: 15:49
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<script src="http://libs.baidu.com/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$("#username").blur(function() {
$.ajax({
type: "get",
url: "RegController?username=" + $("#username").val(),
success: function(data){
$("#loading").remove() ;
//$("#msg").html(msg);
alert(data.msg) ;
},
beforeSend: function() {
$("body").append($("<img>").attr({"src":"image/loading.gif","id":"loading"})) ;
}
});
$.get("RegController",function(msg){
$(msg.hello).each(function(index,d){
$("#msg").html(d.borndate + ":" + d.studentNO) ;
}) ;
}) ;
}) ;
}) ;
</script>
</head>
<body>
<input type="text" name="username" id="username" />
<span id="msg"></span>
</body>
</html>
get/post方法
get 与post区别
- 安全性:get方式请求参数会拼接到url后面,安全性低,post请求参数会包裹在请求体中,安全性高
- 传输数量:get方式传输数据量小,不能超过2kb,post传输数据量大
- 传输速度:get速度快,post慢
$.get("xxx", {
name: "xxx",
id: 17
}, function(resText, status, xhr) {
console.log(resText)
})
$.post("xxx", {
name: "xxx",
id: 17
}, function(resText, status, xhr) {
console.log(resText)
})
fastjson
在前后端数据传输交互中,经常会遇到字符串(String)与json,XML等格式相互转换与解析,其中json以跨语言,跨前后端的优点在开发中被频繁使用,基本上可以说是标准的数据交换格式。fastjson 是一个java语言编写的高性能且功能完善的JSON库,它采用一种“假定有序快速匹配”的算法,把JSON Parse 的性能提升到了极致。它的接口简单易用,已经被广泛使用在缓存序列化,协议交互,Web输出等各种应用场景中。
- 能够支持将java bean序列化成JSON字符串,也能够将JSON字符串反序列化成Java bean。
- 顾名思义,fastjson操作 JSON的速度是非常快的。
- 无其他包的依赖。
- 使用比较方便。
maven依赖:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<!--(起码1.2.48以上)因为这个版本一下存在漏洞-->
<version>版本根据自己需要</version>
</dependency>
public static final Object parse(String text); // 把JSON文本parse为JSONObject或者JSONArray
public static final JSONObject parseObject(String text); // 把JSON文本parse成JSONObject
public static final <T> T parseObject(String text, Class<T> clazz); // 把JSON文本parse为JavaBeanpublic static final JSONArray parseArray(String text); // 把JSON文本parse成JSONArray
public static final <T> List<T> parseArray(String text, Class<T> clazz); //把JSON文本parse成JavaBean集合
public static final String toJSONString(Object object); // 将JavaBean序列化为JSON文本
public static final String toJSONString(Object object, boolean prettyFormat); // 将JavaBean序列化为带格式的JSON文本
public static final Object toJSON(Object javaObject); //将JavaBean转换为JSONObject或者JSONArray。
java类转换为json字符串
package com.csi.eshop.controller.product;
import com.alibaba.fastjson.JSON;
import com.csi.eshop.domain.Product;
import com.csi.eshop.service.ProductService;
import com.csi.eshop.service.impl.ProductServiceImpl;
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;
import java.util.ArrayList;
import java.util.List;
@WebServlet("/JSON_EACHController")
public class JSON_EACHController extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("application/json;charset=utf-8");
PrintWriter out = resp.getWriter();
ProductService productService = new ProductServiceImpl();
List<Product> list = productService.list();
String s = JSON.toJSONString(list);
out.println(s);
}
}
会输出集合以及数组对象
resp.setContentType("application/json;charset=utf-8");
使客户端浏览器,区分不同种类的数据,并根据不同的MIME调用浏览器内不同的程序嵌入模块来处理相应的数据。
实际应用
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
Created by IntelliJ IDEA.
User: 华为
Date: 2022/8/20
Time: 22:12
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"
integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<!-- <script type="text/javascript" src="json/no3.js"></script>-->
<!-- 可选的 Bootstrap 主题文件(一般不用引入) -->
<!-- <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap-theme.min.css" integrity="sha384-6pzBo3FDv/PJ8r2KRkGHifhEocL+1X2rVCTTkUfGk7/0pbek5mMa1upzvWbrUbOZ" crossorigin="anonymous"> -->
<!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"
integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd" crossorigin="anonymous">
</script>
<script type="text/javascript">
$.ajax({
type: "get",
url: "JSON_EACHController",
success: function (msg) {
// $("#loading").remove() ;
//$("#msg").html(msg);
// alert(msg) ;
$.each(msg, function (index, item) {
$("#list").html($("#list").html() +
"<div class='col-sm-6 col-md-3'>" +
"<div class='thumbnail'>" +
"<img id='img1' src='" + item.fileName + "' alt='猥琐的图片路径' >" +
"<div class='caption'>" +
"<h3>" + item.name + "</h3>" +
"<p>" + item.description + "</p>" +
"<p>" + item.price + "</p>" +
"<p>" + "<a href='#' class='btn btn-primary' role='button'>购买</a>" + "<a href='#' class='btn btn-default' role='button'>加入购物车</a>" + "</p>" +
"</div>" +
"</div>" +
"</div>"
)
})
},
});
</script>
</head>
<body>
<div class="row" id="list">
<!-- <div class="col-sm-6 col-md-3">-->
<!-- <div class="thumbnail">-->
<!-- <img src="images/per_1.jpg" alt="...">-->
<!-- <div class="caption">-->
<!-- <h3>Dior/迪奥 真我香水EDP 克丽丝汀</h3>-->
<!-- <p>开业巨惠,北京专柜直供”,不光低价,“真”才靠谱!</p>-->
<!-- <p><a href="#" class="btn btn-primary" role="button">购买</a> <a href="#" class="btn btn-default" role="button">加入购物车</a></p>-->
<!-- </div>-->
<!-- </div>-->
<!-- </div>-->
</div>
</body>
</html>
日期格式处理
数组和集合
import com.alibaba.fastjson.JSON;
import domain.Grade;
import domain.Result;
import domain.Student;
import org.junit.Test;
import java.util.*;
public class test1 {
@Test
public void test1(){
Result result = new Result(200,"成功");
String jsonStr = JSON.toJSONString(result);
System.out.println(jsonStr);
}
@Test
public void test2(){
Student student = new Student();
student.setStudentNo("10001");
student.setBornDate(new Date());
Grade grade = new Grade();
grade.setGradeName("一年");
grade.setGradeId(1);
Set<Student> students = new HashSet<>();
students.add(student);
grade.setStudents(students);
student.setGrade(grade);
String jsonStr = JSON.toJSONString(student);
System.out.println(jsonStr);
}
@Test
public void test3(){
Grade grade = new Grade();
grade.setGradeName("一年");
grade.setGradeId(1);
Student student1 = new Student();
student1.setStudentNo("10001");
student1.setBornDate(new Date());
Student student2 = new Student();
student2.setStudentNo("10002");
student2.setBornDate(new Date());
Set<Student> students = new HashSet<>();
students.add(student1);
students.add(student2);
grade.setStudents(students);
String s = JSON.toJSONString(grade,true);
System.out.println(s);
}
@Test
public void test4(){
//
Grade grade = new Grade();
grade.setGradeName("一年");
grade.setGradeId(1);
Student student1 = new Student();
student1.setStudentNo("10001");
student1.setBornDate(new Date());
Student student2 = new Student();
student2.setStudentNo("10002");
student2.setBornDate(new Date());
List<Student> studentList = new ArrayList<>();
studentList.add(student1);
studentList.add(student2);
String s = JSON.toJSONString(studentList);
System.out.println(s);
Set<Student> students = new HashSet<>();
students.add(student1);
students.add(student2);
grade.setStudents(students);
String s1 = JSON.toJSONString(grade);
System.out.println(s1);
Map<String,Student> map = new HashMap<>();
map.put("key1",student1);
map.put("key2",student2);
String giao = JSON.toJSONString(map,true);
System.out.println(giao);
//
}
@Test
public void test5(){
//
Student student1 = new Student();
student1.setStudentNo("10001");
student1.setBornDate(new Date());
String giao = JSON.toJSONString(student1);
System.out.println(giao);
//
}
}
List[{对象}]
Set{[{对象}]}文章来源:https://www.toymoban.com/news/detail-488665.html
Map{对象}文章来源地址https://www.toymoban.com/news/detail-488665.html
到了这里,关于AJAX与JSON数据交互处理的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!