需求:点击发送请求,将相应信息返回显示至ajax中 页面不刷新
基于上一个Ajax的案例,上一个案例 页面是这样的:【点击发送请求,在框框中显示相关数据】
这里js还是用的server.js
const { response } = require('express');
const express = require('express');
const app = express();
app.get('/server',(request,response)=>{
response.setHeader('Access-Control-Allow-Origin','*');
response.send('HELLO AJAX');
});
app.listen(8000,()=>{
console.log("服务已经启动,8000端口监听中······");
})
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>Ajax GET 请求</title>
<style type="text/css">
#result{
width: 200px;
height: 100px;
border: 1px solid #90b;
}
</style>
</head>
<body>
<!-- 需求:点击发送请求,将相应信息返回显示至ajax中 页面不刷新 -->
<button>点击发送请求</button>
<div id="result"></div>
<script>
const btn = document.getElementsByTagName('button')[0];
const result = document.getElementById("result");
btn.onclick = function(){
const xhr = new XMLHttpRequest();
xhr.open('GET','http://127.0.0.1:8000/server');
xhr.send();
xhr.onreadystatechange = function(){
if(xhr.readyState === 4){
if(xhr.status >= 200 && xhr.status < 300){
result.innerHTML = xhr.response;
}else{
}
}
}
}
</script>
</body>
</html>
运行之后:
|