好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

SpringMVC通过Ajax处理Json数据的步骤详解

SpringMVC通过Ajax处理Json数据的实现

一、前言:

Ajax:
在不重新加载整个页面的前提下,对网页的部分进行刷新,例如点赞,发送短信验证码功能等等,都可以通过ajax进行实现,Ajax实现了网页的异步刷新

想要实现的效果,点击按钮,前端显示后台发送过来的学生信息,本次我们使用jquery形式的Ajax来完成

二、使用步骤

 1.引入jar

jar:
jackson-annotation.jar
jackson-core.jar
jackson-datebind.jar

如果不使用Maven,引入时要确保jar包版本一致问题,否则会引发异常

2.Person类

?

1

2

3

4

jar:

jackson-annotation.jar

jackson-core.jar

jackson-datebind.jar

3.前端页面

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

package com.lanqiao.entity;

 

public class Person {

     private int id;

     private String name;

     private int age;

     public Person() {

         super ();

         // TODO Auto-generated constructor stub

     }

     public Person( int id, String name, int age) {

         super ();

         this .id = id;

         this .name = name;

         this .age = age;

     }

     public int getId() {

         return id;

     }

     public void setId( int id) {

         this .id = id;

     }

     public String getName() {

         return name;

     }

     public void setName(String name) {

         this .name = name;

     }

     public int getAge() {

         return age;

     }

     public void setAge( int age) {

         this .age = age;

     }  

}

4.Controller

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

<%@ page language= "java" contentType= "text/html; charset=UTF-8"

     pageEncoding= "UTF-8" language= "java" isErrorPage= "true" %>

<!DOCTYPE html>

<html>

<head>

<meta charset= "UTF-8" >

<title>Insert title here</title>

</head>

<script type= "text/javascript" src= "js/jquery-3.4.1.js" ></script>

<script type= "text/javascript" >

     $(function () {

         $( "#testJson" ).click(function(){

             //通过Ajax请求springmvc

             $.post(

                 //请求的服务器地址

                 "testJson" ,

                 //服务端处理完毕的回调函数

                 function (result) {

                     for (var i= 0 ;i<result.length;i++){

                         alert(result[i].id+ "," +result[i].name+ "," +result[i].age);

                     }

                 }

             )

         });

     });

</script>

<body>

     <input type= "button" value= "testJson" id= "testJson" >

</body>

</html>

@ResponseBody修饰的方法,会将该方法的返回值以一个json数组的形式返回给前台,它告诉SpringMVC,此时的返回不是一个View页面,而是一个ajax调用的返回值(Json数组)

## 5.测试

到此这篇关于SpringMVC通过Ajax处理Json数据的步骤详解的文章就介绍到这了,更多相关SpringMVC处理Json数据内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

原文链接:https://blog.csdn.net/wenwenaier/article/details/115443794

查看更多关于SpringMVC通过Ajax处理Json数据的步骤详解的详细内容...

  阅读:26次