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”
}
格式化显示出结果!!