SpringBoot前端Ajax以JSON格式获取后台数据

最近在用Thymeleaf做一个项目,耳边总是飘过前后端分离的话语,不得不去了解一下,在Thymeleaf里如何获取后端的json串,这里进行详细的讲解一下(困扰了我好久/哭了)
首先我们需要一个Controller,这个Controller用于视图的跳转,也就是走视图解析器的,当你访问一个网址时,他给你跳转到一个页面

package com.hzy.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class Controller1 {
    @RequestMapping(value = "/hello",method = RequestMethod.GET)
    public String hello(){
        return "hello";
    }
}

当我们访问http://localhost:8080/hello的时候,会跳转到hello.html页面,我们写一个hello.html页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
</head>
<body>
<button id="abc" type="button" value="按钮">按钮</button>
    <script type="text/javascript">
        $("#abc").click(function () {
            $.ajax({
                url: '/getJson',
                type: 'get',
                dataType: 'json',
                data:JSON.stringify('jsonObject'),
                success:function(data){
                    alert(data.msg);
                },
                error:function(){
                    alert('服务器超时,请重试!');
                }
            });
        })
    </script>
</body>
</html>

这里的json就是从那个url里获取的,我们需要写一个controller,这个controller直接返回字符串,而不用走视图解析器

package com.hzy.controller;

import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class Controller2 {
    @RequestMapping(value = "/getJson")
    @ResponseBody
    public String getJson () {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code",0);
        jsonObject.put("msg","成功");
        return jsonObject.toJSONString();
    }
}

这样当我们访问http://localhost:8080/hello的时候,就可以直接获取到json串了
在这里插入图片描述

发布了459 篇原创文章 · 获赞 298 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/HeZhiYing_/article/details/104857719
今日推荐