前端实战-AJAX

引言

这份HTML文档是一个完整的AJAX学习示例,展示了多种AJAX请求方式和相关问题的解决方案。AJAX (Asynchronous JavaScript and XML) 是一种在不重新加载整个页面的情况下,与服务器交换数据并更新部分网页的技术。

效果呈现

源码

<!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>
        #resultget {
            width: 500px;
            height:100px;
            border:solid 1px #000000;
        }
        #resultpost {
            width: 500px;
            height:100px;
            border:solid 1px #004b35;
        }
        #resultjson {
            width: 500px;
            height:100px;
            border:solid 1px #198722bd;
        }
        #resultIE {
            width: 500px;
            height:100px;
            border:solid 3px #bbb102;
        }
        #resulttimeout{
            width: 500px;
            height:100px;
            border:solid 3px #b62b04;
        }
        #resultcancel{
            width: 500px;
            height:100px;
            border:solid 3px #0077be;
        }
    </style>
    </head>
<body>
    
    <!-- GET请求部分 -->
    <div>
        <h1>AJAX GET 请求</h1>
        <p>通过 XMLHttpRequest 对象发送 GET 请求,获取服务器数据。</p>
        <button id="btnget">发送请求</button>
        <div id="resultget"></div>
        <script src="./get.js"></script>
    </div>
    <!-- POST请求部分 -->
    <div>
        <h1>AJAX POST 请求</h1>
        <p>通过 XMLHttpRequest 对象发送 POST 请求,提交数据到服务器。</p>
        <button id="btnpost">鼠标移到框内</button>
        <div id="resultpost"></div>
        <script src="./post.js"></script>
    </div>
    <!-- JSON 数据解析 -->
    <div>
        <h1>演示服务端响应JSON数据</h1>
        <p>通过 XMLHttpRequest 对象发送 GET 请求,获取JSON数据。</p>
        <button id="btnjson">发送请求</button>
        <div id="resultjson"></div>
        <script src="./jsontest.js"></script>
    </div>
    <!-- 解决IE浏览器缓存问题 -->
    <div>
        <h1>解决IE浏览器缓存问题</h1>
        <p></p>
        <button id="btnIE">点击发送请求</button>
        <div id="resultIE"></div>
        <script src="./problem.js"></script>
    </div>
    <!-- 解决请求超时与服务器异常 -->
    <div>
        <h1>解决请求超时与服务器异常</h1>
        <p></p>
        <button id="btntimeout">点击发送请求</button>
        <div id="resulttimeout"></div>
        <script src="./timeout.js"></script>
    </div>
    <!-- 发送请求和取消请求 -->
     <div>
        <h1>发送请求和取消请求</h1>
        <p>通过 XMLHttpRequest 对象发送 GET 请求,获取服务器数据。</p>
        <button id="btnsend">发送请求</button>
        <button id="btncancel">取消请求</button>
        <div id="resultcancel"></div>
        <script src="./cancel.js"></script>
     </div>
     <!-- 解决重复请求问题 -->
      <div>
        <h1>解决重复请求问题</h1>
        <p>通过 XMLHttpRequest 对象发送 GET 请求,获取服务器数据。</p>
        <button id="btnrepeat">发送请求</button>
        <div id="resultrepeat"></div>
        <script src="./repeat.js"></script>
      </div>
</body>
</html>

js部分

get.js

const btn = document.getElementById('btnget');
const resultget = document.getElementById('resultget');
//绑定事件
btn.onclick = () => {
    
    console.log('发送请求成功');
    //创建 XMLHttpRequest 对象
    const xhr = new XMLHttpRequest();
    //初始化 设置请求方法和url
    xhr.open('GET', 'http://127.0.0.1:8000/server?a=100&b=200&c=300');
    // 发送请求
    xhr.send();
    // 事件绑定,处理服务端返回的结果
    // on when 当... 的时候
    //readyState属性表示xhr对象的状态,0表示请求未初始化,1表示服务器连接已建立,2表示请求已接收,3表示请求处理中,4表示请求已完成,如果状态为4,说明请求已成功完成,可以进行后续操作
    xhr.onreadystatechange = () => {
        // 判断服务器返回了所有的结果
        if(xhr.readyState === 4){
            // 判断响应状态码 200 404 403 401 500
            if(xhr.status === 200){
                //处理结果 行 头 空行 体
                // 响应行
                console.log(xhr.status);//状态码
                console.log(xhr.statusText);//状态描述
                console.log(xhr.getAllResponseHeaders());//所有响应头
                console.log(xhr.response);//响应体

                //设置resultget的文本
                resultget.innerHTML = xhr.response;
            }
        }
    }
}

post.js

//获取元素对象
const result = document.getElementById("resultpost");
//绑定事件
result.addEventListener("mouseover",function(){
    console.log("mouseover");
    //创建对象
    const xhr = new XMLHttpRequest();
    //设置请求方式和请求地址
    xhr.open('POST','http://127.0.0.1:8000/server');
    //设置请求头
    xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
    // 发送
    xhr.send('a=200&b=300');
    // 事件绑定
    xhr.onreadystatechange = function(){
        if(xhr.readyState === 4){
            if(xhr.status >= 200 && xhr.status < 300){
                //处理服务器返回的结果
                result.innerHTML = xhr.responseText;
            }
        }
    }
});

jsontest.js

const resultjson = document.getElementById('resultjson');
// 绑定键盘按下事件
window.onkeydown = function(){
    console.log('绑定成功');
    // 发送请求
    const xhr = new XMLHttpRequest();
    //设置响应体数据类型
    xhr.responseType = 'json';
    // 初始化
    xhr.open('GET', 'http://127.0.0.1:8000/json-server');
    // 发送请求
    xhr.send();
    // 事件绑定
    xhr.onreadystatechange = function(){
        if(xhr.readyState === 4){
            if(xhr.status === 200){
                // console.log(xhr.responseText);
                // resultjson.innerHTML = xhr.responseText; 

                // 1.手动对数据转化
                // let data = JSON.parse(xhr.response);
                // console.log(data);
                // resultjson.innerHTML = data.name;

                //2.自动转化
                console.log(xhr.response);
                resultjson.innerHTML = xhr.response.name;
            }
        }
    }
}

problem.js

const btnIE = document.getElementById('btnIE');
const resultIE = document.querySelector('#resultIE');

btnIE.addEventListener('click', () => {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', 'http://127.0.0.1:8000/ie?t='+Date.now());
    xhr.send();
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4 && xhr.status === 200) { 
            resultIE.innerHTML = xhr.response;
        } 
    }
    
});

timeout.js

const btntimeout = document.getElementById('btntimeout');
const resulttimeout = document.querySelector('#resulttimeout');

btntimeout.addEventListener('click', () => {
    const xhr = new XMLHttpRequest();
    //超时设置 2s
    xhr.timeout = 2000;
    // 超时回调
    xhr.ontimeout = function() {
        resulttimeout.innerHTML = '请求超时';
    };
    // 网络异常回调
    xhr.onerror = function() {
        alert('你的网络似乎出了一点问题');
    };
    xhr.open('GET', 'http://127.0.0.1:8000/delay');
    xhr.send();
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4 && xhr.status === 200) { 
            resulttimeout.innerHTML = xhr.response;
        } 
    }
    
});

cancel.js

const btnSend = document.getElementById('btnsend');
const btnCancel = document.getElementById('btncancel');
const resultCancel = document.getElementById('resultcancel');

let xhr = null;

let isSending = false; //是否正在发送AJAX请求

btnSend.addEventListener('click', () => {
    //判断标识变量
    if(isSending) xhr.abort();//如果请求正在发送则取消该请求只发送一个请求
    xhr = new XMLHttpRequest();
    //修改标识变量的值
    isSending = true;
    xhr.open('GET', 'http://127.0.0.1:8000/delay');
    xhr.send();
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4 && xhr.status === 200) { 
            // 修改标识变量
            isSending = false;
            resultCancel.innerHTML = xhr.response;
        } 
    }
    
});

btnCancel.addEventListener('click', () => {
    xhr.abort();
    resultCancel.innerHTML = '请求已取消';

});

服务器

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

// 添加请求体解析
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

//创建路由规则
// 处理get请求
app.get('/server', (req, res) => {
    // 设置响应头
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Headers', '*');
    // 设置响应体
    res.send('Great! You get it!');
});


// 处理post请求
app.post('/server', (req, res) => {
    // 设置响应头
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Headers', '*');
    // 设置响应体
    res.send('Great! You POST it!');
});

// 处理json请求
app.all('/json-server', (req, res) => {
    // 设置响应头
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Headers', '*');
    // 设置响应体
    // res.send('Great! JSON server is working!');
    // 响应一个数据
    const data = {
        name:'sdwhebdsdfd'
    };
    //对对象进行一个字符串的转换
    let str = JSON.stringify(data);
    res.send(str);
});

// 处理IE请求
app.get('/ie', (req, res) => {
    // 设置响应头
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Headers', '*');
    // 设置响应体
    res.send('Its IE Qusetion!');
});

// 处理错误请求
app.get('/delay', (req, res) => {
    // 设置响应头
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Headers', '*');
    setTimeout(() => {
        // 设置响应体
        res.send('延时响应');
    }, 3000);
    
});

//JQuery请求
app.all('/jquery-server', (req, res) => {
    // 设置响应头
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Headers', '*');
    // 设置响应体
    const data ={name:'JQuery发送的请求'};
    res.send(JSON.stringify(data));
    //res.send('Its JQuery Qusetion!');
}); 

// Axios请求
app.all('/axios-server', (req, res) => {
    // 设置响应头
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Headers', '*');
    // 设置响应体
    const data ={name:'axios发送的请求'};
    res.send(JSON.stringify(data));
    //res.send('Its Axios Qusetion!');
}); 

// 404处理
app.use((req, res) => {
    res.status(404).send('Not Found');
});

//监听端口启动服务
app.listen(8000, () => {
    console.log('Server is running on port 8000');
});

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值