前端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串了
在这里插入图片描述

  • 3
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

贺志营

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值