Ajax学习(3)--基本示例

98 阅读1分钟

基本样例

搭建一个简单的通信。

1.html代码如下所示

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Ajax GET</title>
    <style>
        #response{
            width: 100px;
            height: 100px;
            border: solid 1px;

        }
    </style>
</head>
<body>
    <button>button</button>
    <div id="response"></div>

    <script>
        const btn = document.getElementsByTagName('button')[0];
        const response = document.getElementById("response");
        btn.onclick = function(){

            //1.创建对象
            const xhr = new XMLHttpRequest();

            //2.初始化
            xhr.open('GET','http://127.0.0.1:8080/server');

            //3.发送
            xhr.send();

            xhr.onreadystatechange = function(){
                if(xhr.readyState === 4){
                    //服务端返回了所有的结果
                    // if(xhr.status === 200){
                    if(xhr.status >= 200 && xhr.status < 300){
                        //处理结果
                        console.log(xhr.status);//状态码
                        console.log(xhr.statusText);//状态字符串
                        console.log(xhr.getAllResponseHeaders());//所有相应头
                        console.log(xhr.response);//响应体

                        response.innerHTML = xhr.response;
                    }
                }
            }
        }
    </script>
</body>
</html>

2.服务器端代码如下所示

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

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

//3. 创建路由规则
app.get('/server',(request,response)=>{
    //设置相应头
    response.setHeader('Access-Control-Allow-Origin','*');
    response.send("this is response");
})

// 4. 监听端口启动服务
app.listen(8080,()=>{
    console.log("start 8080...");
})

image.png

启动server.js后在网页中打开html,点击摁扭便可以进行通信,在文本框中会显示response的内容。相关状态码,字符串等可以在F12控制台中查看。

image.png

制作不易还希望各位老板点个赞支持。