后端发出请求,前端进行接收(AJAX)

<!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>

  

 

posted on 2023-02-07 23:54  爱前端的小魏  阅读(27)  评论(0编辑  收藏  举报

导航