AJAX基础知识(2)-JSON响应
server.js文件
//1. 引入express
const express = require('express');
//2. 创建应用对象
const app = express();
//3. 创建路由规则
//JSON 响应
app.all('/json-server', (request, response) => {
//设置响应头 设置允许跨域
response.setHeader('Access-Control-Allow-Origin', '*');
//响应头
response.setHeader('Access-Control-Allow-Headers', '*');
//响应一个数据
const data = {
name: 'JSON'
};
//把对象进行字符串转换
let str = JSON.stringify(data);
//设置响应体
response.send(str);
});
//4. 监听端口启动服务
app.listen(8000, () => {
console.log("服务已经启动, 8000 端口监听中....");
});
<style>
#result {
width: 200px;
height: 100px;
border: solid 1px #89b;
}
</style>
</head>
<body>
<div id="result"></div>
<script>
const result = document.getElementById("result");
//绑定键盘按下事件
window.onkeydown = function () {
//发送请求
const xhr = new XMLHttpRequest();
//设置响应体数据的类型
xhr.responseType = "json";
//初始化
xhr.open("GET", "http://127.0.0.1:8000/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>
我们的需求是绑定键盘事件,按下键盘则将JSON文字显示在方框中,效果如下面的图所示:
按下键盘