微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

AJAX 发送请求一

使用get发送请求
点击按钮时获取ajax的状态,在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>AJAX GET 请求</title>
    <style>
        #result{
            width: 200px;
            height: 100px;
            border: solid 1px pink;
        }
    </style>
</head>
<body>
    <button>点击发送请求</button>
    <div id="result"></div>
    <script>
        const btn = document.querySelector('button');
        const result = document.querySelector('#result');
        btn.onclick = function(){
            const xhr = new XMLHttpRequest(); 
            xhr.open('GET','http://127.0.0.1:8000/server?a=100&b=200&c=300');
            xhr.send();
            xhr.onreadystatechange = function(){
                if(xhr.readyState === 4){
                    if(xhr.status >= 200 && xhr.status < 300){
                        console.log(xhr.status); //状态码
                        console.log(xhr.statusText); // 状态字符串
                        console.log(xhr.getAllResponseHeaders()); //所有响应头
                        console.log(xhr.response);//响应体
                        result.innerHTML = xhr.response;
                    }else{

                    }
                }
            }
        }
    </script>
</body>
</html>

在这里插入图片描述初始时的html

用node 添加 服务器代码

const express = require('express');
const app = express();
 app.get('/server', (request, response) => {
    response.setHeader('Access-Control-Allow-Origin', '*');
    response.send('HELLO AJAX');//在页面输出 HELLO AJAX
 });
app.listen(8000, () => {
    console.log('服务器已经启动,8000端口监听中'); // 若服务器成功,在终端输出'服务器已经启动,8000端口监听中'
})

在这里插入图片描述控制台

查看报文

在这里插入图片描述符合要求

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐