我正在尝试使用JSON字符串填充JSP页面中的表。我在JSP页面中的Ajax脚本:
function getData() {
$.ajax({
url: 'ajaxtest',
success: function (data) {
response = $.parseJSON(data);
$.each(response, function (i, item) {
$('<tr>').append(
$('<td>').text(item.id),
$('<td>').text(item.name),
$('<td>').text(item.answer),
$('<td>').text(item.code),
$('<td>').text(item.created),
$('<td>').text(item.state)).appendTo('#records_table');
});
}
});
}
间隔:
var intervalId = 0;
intervalId = setInterval(getData, 3000);
控制器:
@RequestMapping(value = "/ajaxtest", method = RequestMethod.GET)
public @ResponseBody
String getAnswers() {
List<Answer> result1 = answerService.getAnswers();
Gson gson = new Gson();
String result = gson.toJson(result1);
return result;
}
正如您所看到的,我正在从控制器中检索一个String,我在JSP页面中使用它来发送请求。在一个foreach我填充我的表,这是有效的。但问题是,它会在每次请求(3秒)后继续打印出所有项目
有没有办法用ajax作为前缀或检查一行是否已存在?
修改: 使用
吐出数据时$('#result').html(data);
和
<div id="result"></div>
我得到以下
[{"id":43,"name":"answer 1","answer":"answer of the question","code":2260,"created":"Jan 23, 2016","state":"LOCKED"},{"id":32,"name":"answer 2","answer":"answer of the question 2","code":7940,"created":"Jan 13, 2016","state":"ACTIVE"}]