前端基础知识---Ajax

1 Ajax、XML简介

1.1 Ajax简介

Ajax是异步的js和XML,无刷新获取数据

优点:(1)无刷新页面与服务端通信

(2)可根据用户事件更新部分页面

缺点:(1)无浏览历史,不可后退

(2)存在跨域问题

(3)SEO不友好

1.2 XML简介

XML可拓展标记语言,设计于传输和存储数据,现已被JSON替代

2 HTTP协议

约定了服务器和浏览器之间的互相通信的规则。(请求报文和响应报文)

请求报文:(POST请求才有请求体,GET的请求体为空)

响应报文:

html是放在响应体中的。

浏览器在接受到服务器发来的响应体之后,提取html内容进行解析,再渲染在页面中。

2 案例

2.1 GET.html

html 复制代码
<style>
    #result{
        width: 200px;
        height:100px;
        border: solid 1px #989898;
    }
</style>

<body>
    <button>点击发送请求</button>
    <div id="result"></div>
</body>

<script>
    //获取button元素
    const btn = document.getElementsByTagName('button')[0]
    const result = document.getElementById('result')
    //绑定事件
    btn.onclick = function(){
        //1.创建对象
        const xhr = new XMLHttpRequest();
        //2.初始化 设置请求方法和url
        xhr.open('GET','http://127.0.0.1:8000/server?a=100&&b=200')
        //3.发送
        xhr.send()
        //4.事件绑定
        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.getResponseHeader())//所有响应头
                //     }
                    //设置result的文本
                    result.innerHTML = xhr.response;
            }
        }

    }
</script>

2.2 POST.html

html 复制代码
<style>
    #result{
        width: 200px;
        height: 100px;
        border: solid 1px #939393;
        
    }
</style>
<body>
    <div id="result"></div>
</body>
<script>
    //获取元素对象
    const result = document.getElementById('result');
    //绑定事件
    result.addEventListener("mouseover",function(){
        //1.创建对象
        const xhr = new XMLHttpRequest();
        //2.初始化 设置类型与url
        xhr.open('POST','http://127.0.0.1:8000/server');
        //设置请求头
        xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
        //3.发送
        xhr.send('123456')
        //4.事件绑定
        xhr.onreadystatechange = function(){
            if(xhr.readyState ===4){
                if(xhr.status >=200&&xhr.status<300){
                    result.innerHTML = xhr.response;
                }
            }
        }
    })
    

</script>

2.3 JSON.html

html 复制代码
<style>
    #result{
        width: 200px;
        height: 100px;
        border: solid 1px #898989;
    }
</style>
<body>
    <div id="result"></div>
</body>

<script>
    //绑定键盘按下事件
    window.onkeydown = function(){
        //创建对象
        const xhr = new XMLHttpRequest();
        //初始化
        xhr.open('GET','http:127.0.0.1:8000/json-server')
        //发送
        xhr.send();
        //事件绑定
        xhr.onreadystatechange = function(){
    if(xhr.readyState === 4){ // 请求完成
        if(xhr.status >= 200 && xhr.status < 300){ // 响应成功
            // 解析后端返回的JSON字符串为对象
            const data = JSON.parse(xhr.responseText);
            // 将数据渲染到页面
            result.innerHTML = data.name;
        }
    }
}
    }
</script>

sever.js

javascript 复制代码
const express = require('express')  //引入express包
const app = express();  //创建应用对象
app.get('/server',(req,res)=>{    //创建路由规则
    //设置响应头,允许跨域
    res.setHeader('Access-Control-Allow-Origin','*')
    res.send('hello ajax')
});
app.post('/server',(req,res)=>{    //创建路由规则
    //设置响应头,允许跨域
    res.setHeader('Access-Control-Allow-Origin','*')
    res.send('hello ajax post')
});
app.all('/json-server',(req,res)=>{    //创建路由规则
    //设置响应头,允许跨域
    res.setHeader('Access-Control-Allow-Origin','*')


    //响应一个数据
    const data = {
        name:'aguigu'
    }
    //对对象进行字符串转换
    let str = JSON.stringify(data)
    res.send(str)
});

app.listen(8000,()=>{   //监听
    console.log('服务器已经启动,8000端口监听中')
})

3 IE缓存问题

xhr.open('POST','http://127.0.0.1:8000/ie?t='+Date.now());

每次都不一样,就不会拿到缓存结果

4 请求超时与网络异常问题

复制代码
html
//超时2s设置
            xhr.timeout = 2000;
            //超时回调
            xhr.ontimeout = function(){
                alert('网络异常,请稍后重试!')
            }
            //网络异常回调
            xhr.onerror = function(){
                alert('你的网络似乎出现了一些问题')

js
app.get('/delay',(req,res)=>{    //创建路由规则
    //设置响应头,允许跨域
    res.setHeader('Access-Control-Allow-Origin','*')
    setTimeout(()=>{
        res.send('延时响应')
    },3000)
    
});

5 取消重复请求(设置标识变量)

abort()

javascript 复制代码
//标识变量
    let isSending = false;// 初始值为 false,表示"当前没有正在发送的 AJAX 请求"


    btns[0].onclick = function(){
        if(isSending) x.abort();   //如果有ajax请求正在发送,则终止操作
        x = new XMLHttpRequest();   //终止操作后,创建新对象
        //修改标识变量
        isSending = true;
        x.open('GET','http://127.0.0.1:8000/delay')
        x.send();
        x.onreadystatechange = function(){
            if(x.readyState ===4){
                //修改标识变量
                isSending = false;
            }
        }
    }

6 jQuery发送Ajax请求

(1)引入jQuery

复制代码
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

(2)最基础的jQuery方法

复制代码
$.ajax({
  url: '请求的服务器地址',  // 必选,如 'http://localhost:8000/data'
  type: '请求方法',         // 可选,默认 'GET',常用 'GET'/'POST'
  data: '要发送的数据',      // 可选,如 {name: '张三', age: 20} 或 'name=张三&age=20'
  dataType: '预期的响应数据类型',  // 可选,如 'json'(自动解析JSON)、'html'、'text'
  success: function(res) {   // 可选,请求成功后的回调函数,res 是服务器返回的数据
    console.log('请求成功', res);
  },
  error: function(xhr) {     // 可选,请求失败后的回调函数,xhr 是错误信息对象
    console.log('请求失败', xhr);
  },
  timeout: 3000              // 可选,超时时间(毫秒),超过时间则触发 error
});

7 同源策略(来自于同一个服务器)

同源:协议、域名、端口号必须完全相同(Ajax默认遵循同源策略)

相关推荐
AI智能研究院4 小时前
(四)从零学 React Props:数据传递 + 实战案例 + 避坑指南
前端·javascript·react.js
qq7798233404 小时前
React组件完全指南
前端·javascript·react.js
EndingCoder4 小时前
MongoDB基础与Mongoose ODM
服务器·javascript·数据库·mongodb·中间件·node.js
qq7798233404 小时前
React Hooks完全指南
前端·javascript·react.js
Moment4 小时前
性能狂飙!Next.js 16 重磅发布:Turbopack 稳定、编译提速 10 倍!🚀🚀🚀
前端·javascript·后端
软件技术NINI4 小时前
html css js网页制作成品——HTML+CSS仙台有树电视剧网页设计(5页)附源码
javascript·css·html
DoraBigHead5 小时前
React Fiber:从“递归地狱”到“时间切片”的重生之路
前端·javascript·react.js
YUELEI1185 小时前
Vue 安装依赖的集合和小知识
javascript·vue.js·ecmascript
lecepin6 小时前
AI Coding 资讯 2025-10-22
前端·javascript·后端