當(dāng)前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
JSON响应
response.send(str)? ? ? ? ? ? ? 服務(wù)器發(fā)送的響應(yīng)體
xhr.response? ? ? ? ? ? ? ? ? ? ? ? 客戶端接收的響應(yīng)體
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>JSON響應(yīng)</title><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(){//發(fā)送請求const xhr = new XMLHttpRequest();//設(shè)置響應(yīng)體數(shù)據(jù)的類型xhr.responseType = 'json';//初始化xhr.open('GET','http://127.0.0.1:8000/json-server');//發(fā)送xhr.send();//事件綁定xhr.onreadystatechange = function(){if(xhr.readyState === 4){if(xhr.status >= 200 && xhr.status < 300){//// console.log(xhr.response);// result.innerHTML = xhr.response;// 1. 手動對數(shù)據(jù)轉(zhuǎn)化// let data = JSON.parse(xhr.response);// console.log(data);// result.innerHTML = data.name;// 2. 自動轉(zhuǎn)換console.log(xhr.response);result.innerHTML = xhr.response.name;}}}}</script> </body> </html>總結(jié)
- 上一篇: AJAX POST 请求
- 下一篇: AJAX-nodemon自动重启工具安装