HTML
<!DOCTYPE html>
<html lang="en">
<head>
<Meta charset="UTF-8">
<Meta http-equiv="X-UA-Compatible" content="IE=edge">
<Meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JSON响应</title>
<style>
#result{
width: 200px;
height: 100px;
border: solid 1px #ccc;
}
</style>
</head>
<body>
<div id="result"></div>
<script>
const result = document.querySelector('#result');
window.addEventListener('keydown',function(){
const xhr = new XMLHttpRequest();
xhr.responseType = 'json'; //自动转换将json转换成object
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;
// let data = JSON.parse(xhr.response);//json转object
// console.log(data);
console.log(xhr.response);
// result.innerHTML = data.name;
result.innerHTML = xhr.response.name;
}
}
}
})
</script>
</body>
</html>
node
const express = require('express');
const app = express();
app.get('/json-server', (request, response) => {
response.setHeader('Access-Control-Allow-Origin', '*');
const data = {
name:'andy',
}
let str = JSON.stringify(data) //object 转 json
response.send(str);
});
app.listen(8000, () => {
console.log('服务器已经启动,8000端口监听中');
})
最终结果
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。