后端controller:
@RequestMapping(value = "/json-server")
@ResponseBody
public Map test03(HttpServletRequest req, HttpServletResponse resp){
resp.setHeader("Access-Control-Allow-Origin","*");
Map<String, String> data = new HashMap<String, String>();
data.put("name","张三");
return data;
}
前端页面(设置键盘按下事件并响应):
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>JSON响应</title>
<style>
#result{
width: 200px;
height: 100px;
border: solid 1px #00ff00;
}
</style>
</head>
<body>
<div id="result"></div>
<script>
var result = document.getElementById('result');
window.onkeydown = function(){
let xhr = new XMLHttpRequest();
xhr.responseType = 'json';
xhr.open('GET','http://127.0.0.1:8080/json-server');
xhr.send();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4){
if (xhr.status >= 200 && xhr.status < 300){
console.log(xhr.response);
result.innerHTML = xhr.response.name;
}
}
}
}
</script>
</body>
</html>
初始化
按下键盘事件
查看响应体