我正在尝试使用Json将我的数据列表转换为字符串,并将其返回到Ajax以填充数据表。 Spring控制器能够将它转换为Json数据,但是如果从Spring返回并让它在Ajax中取得成功令人困惑,任何人都可以帮助我。以下是我的代码详情,
控制器类
@Controller
@RequestMapping(value = "/json")
public class JsonController {
@RequestMapping(value = "/postEmployee", method = RequestMethod.POST, produces = "application/json")
public @ResponseBody
String postEmployeeData() throws JsonGenerationException,
JsonMappingException, IOException {
List<Users> users = new ArrayList<Users>();
for (int i = 0; i < 5; i++) {
Users user = new Users();
user.setName("Akram");
user.setPrincipal("DEC");
users.add(user);
}
ObjectMapper mapper = new ObjectMapper();
String data = mapper.writeValueAsString(users);
return data;
}
Jquery的
<script type="text/javascript">
$("#submit").click(function() {
$.ajax({
type : "post",
url : "/myApp/json/postEmployee.do",
cache : false,
success : function(response) {
display(response);
alert('Inside success');
var obj = JSON.parse(response);
alert(obj);
},
error : function() {
alert('Error while request..');
}
});
});
</script>
在POM.xml中
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.6.3</version>
</dependency>
这里没有得到回复。所以请帮助我实现这一目标。
答案 0 :(得分:0)
如果你有一个正确配置的Spring应用程序它可以返回一个json值,你可以直接返回一个列表。
(...)
public @ResponseBody List<Users> postEmployeeData() {
(...)
return users;
}
答案 1 :(得分:0)
为什么不使用ResponseEntity
发送回复?
@RequestMapping(value = "/postEmployee", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity List<Users> postEmployeeData() throws JsonGenerationException, JsonMappingException, IOException {
List<Users> users = new ArrayList<Users> ();
for (int i = 0; i < 5; i++) {
Users user = new Users();
user.setName("Akram");
user.setPrincipal("DEC");
users.add(user);
}
return ResponseEntity<>(users, HttpStatus.OK);
}
更改
<强>加强>
method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE
public ResponseEntity List<Users> postEmployeeData() ...
return ResponseEntity<>(users, HttpStatus.OK);
<强>删除强>
ObjectMapper mapper = new ObjectMapper();
String data = mapper.writeValueAsString(users);
return data;