<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <style> #result { width: 300px; height: 100px; border: 1px solid red; } </style> </head> <body> <div id="result"></div> </body> <script type="text/javascript"> //获取元素 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(); //事件绑定1 xhr.onreadystatechange = function() { if(xhr.readyState === 4) { if(xhr.status >= 200 && xhr.status < 300){ //手动获取数据 // let data = JSON.parse(xhr.response); // console.log(data) // result.innerHTML = data.name; //自动获取数据 使用方法:xhr.responseType = 'json'; console.log(xhr.response) let data = xhr.response result.innerHTML = data.name; } } } } </script> </html>
标签:发出请求,获取数据,前端,json,xhr,AJAX,result,data,response From: https://www.cnblogs.com/wsx123/p/17100222.html