Spring 后端传输Json数据并格式化显示

本文详细介绍如何在SpringMVC中使用@ResponseBody注解返回JSON格式的数据,并通过Ajax异步请求获取这些数据,同时展示了如何在前端使用JSONView插件解析并显示JSON数据。

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

1、首先Spring mvc服务器返回Json数据-String字符串
需要添加@ResponseBody,代码:

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class GoViews {

    @RequestMapping("goView")
    @ResponseBody
    public String goNewView(String name, Model model) {
        model.addAttribute("name", name);
        String result = "{\n" +
                "\t\"A\": \"Test\",\n" +
                "\t\"Name\": \"Action\"\n" +
                "}";
        return result;
    }
}

2、前端使用Ajax异步访问后端,刷新界面,这里面用到了一个插件,可以看Json-view插件使用,然后另外指出如果使用插件js里面,报错 $("").JSONView(json) is not a function,需要看另一篇博客,感谢下博主jsp不能引用js,cs等解决办法,最后贴下前端代码:

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
    <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
    <script type="text/javascript" src="jquery.jsonview.js"></script>
    <script type="text/javascript">
        function goNewWindow() {
            $.ajax({
                type: "POST",
                url: "/goView",
                contentType: "application/json;charset=utf-8",
                dataType: "json",
                data: {name: name},
                success:function(data){
                    var json = eval(data);
                    $.each(json, function(index, element) {
                        alert(element.a);
                        alert(element.b);
                    });

                    //$('#result').html();
                    $("#result").JSONView(json);
                }
            });
        }

    </script>
</head>
<body>
<input type="button" name="按键" onclick="goNewWindow()"/>
<tr></tr>
结果:
<div id="result" ></div>
</body>
</html>

3、最后的结果:
{
“A”: “Test”,
“Name”: “Action”
}
格式化显示出结果!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值