SpringMVC返回JSON数据的坑

xiaoxiao2021-02-28  126

测试一:


@RequestMapping(value = "/test1", method = RequestMethod.POST) @ResponseBody public Person test1() { Person person = new Person(); person.setName("熙雅"); person.setAge(24); person.setBirth(new Date()); person.setId(1); person.setEmail("lgh1992314@qq.com"); return person; } <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <script src="static/js/jquery-3.2.1.min.js"></script> <title>学习</title> <script> $(function () { $.post("http://localhost:8080/SSMCRUD/test1", function(data) { // data = eval("(" + data+ ")"); $('#name').val(data.name); $('#age').val(data.age); }); }); </script> </head> <body> <input type="text" id="name"/> <input type="text" id="age"/> </body> </html>

当返回对象时,我们不需要使用 eval()来将json字符串转化为javascript对象。

如上图所示,返回的是标准的json字符串格式。

测试二

@RequestMapping(value = "/test1", method = RequestMethod.POST) @ResponseBody public String test1() { Person person = new Person(); person.setName("熙雅"); person.setAge(24); person.setBirth(new Date()); person.setId(1); person.setEmail("lgh1992314@qq.com"); String json = com.alibaba.fastjson.JSON.toJSONString(person); System.out.println(json); return json; // return "{\"name\":\"熙雅\",\"age\":24}"; }

此时,返回的json字符串的格式:

“{\”age\”:24,\”birth\”:1499759417522,\”email\”:\”lgh1992314@qq.com\”,\”id\”:1,\”name\”:\”熙雅\”}”

所以需要eval()函数解析:

<script> $(function () { $.post("http://localhost:8080/SSMCRUD/test1", function(data) { data = eval("(" + data+ ")"); $('#name').val(data.name); $('#age').val(data.age); }); }); </script>

data = eval(“(” + data+ “)”);

为什么eval这里要括号? 由于json是以{ }的方式来开始以及结束的,在eval中会被当成一个语句块来处理,故必须强制将它转换成一种表达式。 加上圆括号是使eval函数在处理时强制将括号内的表达式(expression)转化为对象而不作为语句(statement)来执行。

alert(eval(“{}”));//undefined alert(eval(“({})”));//[Object,Object]

转载请注明原文地址: https://www.6miu.com/read-69079.html

最新回复(0)