AJAX发送POST请求

需求:
当鼠标移入到页面div当中,页面向服务端发送POST请求,服务端将响应结果作为显示体在div中显现出来

前端代码

<!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>Document</title>
    <style>
        #result{
            width: 200px;
            height: 100px;
            border: solid 1px #903;
        }
    </style>
</head>
<body>
    <div id="result"></div>
    <script>
        // 获取对象
        const result=document.getElementById("result");
        // 绑定事件
        result.addEventListener("mouseover",function(){
            // 创建对象
            const xhr=new XMLHttpRequest();
            xhr.open('POST','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;
                    }
                }
            }
        })
    </script>
</body>
</html>

服务端

// 引入express
const express=require('express');

// 创建应用对象
const app=express();

// 创建POST路由规则
app.post('/server',(request,response)=>{
    // 设置响应

    // 设置响应头 设置允许跨域
    response.setHeader('Access-Control-Allow-Origin','*');

    // 响应体
    response.send('HELLO AJAX POST');
});
// 监听端口启动服务
app.listen(8000,()=>{
    console.log("服务已经启动...");
})

结果

查看相应的响应头 响应体 请求头

POST设置请求体

在POST参数的设置是在send()方法中进行设置的

            xhr.send('a=100&b=200&c=300');
            xhr.send('a:200&c:300&b:500');
            xhr.send('123123123');

参数的格式可以是任意格式

POST设置请求头信息

            // 设置请求头
            // Content-Type是来设置 请求体 内容类型 即 xhr.send() 内的类型
            // 后边一长串代表的是 send() 括号里面参数类型查询的固定写法
            xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
            // 发送
            xhr.send('a=100&b=200&c=300');

响应结果

更多推荐

AJAX发送POST请求