请求url直接使用springMVC请求路径:
<script th:inline="javascript">
$(document).ready(function(){$.ajax({
type:"GET",
url:"news/getKeyWords",
success:function(response){
alert(response)
},
error : function(e) {
alert('Failed!: ' + e);
}
});
});
</script>
java端需要将方法定义为void,避免页面跳转,使用HttpServletResponse 返回Ajax请求数据:
@Controller
@RequestMapping("/news")
public class NewsContoller {
@Autowired
private IKeywordService keywordService;
@RequestMapping("/getKeyWords")
public void getKeyWords(HttpServletResponse response) {
List<IKeyword> allKeyWords = keywordService.getAllKeyWords();
try {
String jsonString = JSON.toJSONString(allKeyWords);
response.getWriter().print(jsonString);
} catch (IOException e) {
e.printStackTrace();
}
}
}