ajax请求的步骤

1.客户端

 <script>
 	 //拿到div容器
      const re = document.getElementById("result");
      //绑定div容器事件
      re.addEventListener("mouseover", function () {
    
    
       
        //1 绑定事件
        const xhr = new XMLHttpRequest();
        //2 初始化
        xhr.open("POST", "http://127.0.0.1:8000/server");
        //3发送
        xhr.send();
        //4 事件绑定
        xhr.onreadystatechange = function () {
    
    
          //判断
          if (xhr.readyState == 4) {
    
    
              if (xhr.status >= 200 && xhr.status < 300) {
    
    
                console.log(xhr.status);
                //处理服务端返回结果
                re.innerHTML = xhr.response;  
                 console.log(xhr.response);
            }
          }
        };
      });
    </script>

服务器端

const express = require('express');

const app = express();

app.get('/server', (request, reponse)=>{
    
    
    reponse.setHeader("Access-Control-Allow-Origin","*");
    reponse.send("HELLO");
});

app.post('/server', (request, reponse)=>{
    
    
    reponse.setHeader("Access-Control-Allow-Origin","*");
    reponse.send("HELLO POST");
});

app.listen(8000, ()=>{
    
    
    console.log("8000监听中.....");
});

结果
当鼠标移入框框时,将服务器端的返回的数据在框框中展示出来
在这里插入图片描述
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_45432665/article/details/109221048