Ajax前后端交互的方法

本文介绍了Ajax的基本概念,阐述了其无需刷新页面即可更新内容、响应用户事件的优点,以及存在无浏览历史、跨域限制和SEO问题的缺点。接着详细讲解了原生Ajax、jQuery-Ajax、Axios以及Fetch()的使用方法,并提到了服务器端使用Node.js-Express进行配合的例子。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

ajax简介

  • Ajax :“Asynchronous Javascript And XML”(异步 JavaScript 和 XML)

ajax的优点

  • 无需重新加载整个网页的情况下,能够更新部分网页内容的技术
  • 允许根据用户事件来更新部分网页内容

ajax的缺点

  • 没有浏览历史,不能回退
  • 存在跨域问题,只能访问同源网站内容(解决办法:jsonp/cors设置请求头)
  • SEO不友好

ajax的使用方法

在这里插入图片描述

原生ajax

  • 创建对象:const xhr = new XMLHttpRequest();
  • 设置请求方法:xhr.open('GET', 'http://localhost:8000/server');
  • 发送请求:xhr.send();
  • 处理服务端返回的结果
//get方法发送原生ajax
	const btn = document.getElementsByTagName('button');
	<script>
        btn[0].onclick = function () {
            //创建对象
            const xhr = new XMLHttpRequest();
            //设置请求方法和url
            xhr.open('GET', 'http://localhost:8000/server');
            //发送
            xhr.send();
            //事件绑定 处理服务端返回的结果
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4) { //服务端返回了所有结果
                    if (xhr.status >= 200 && xhr.readyState <= 300) {  
                        //处理结果
                        console.log(xhr.status); //状态码
                        console.log(xhr.statusText); //状态字符串
                        console.log(xhr.getAllResponseHeaders); //所有响应头
                        console.log(xhr.response); //响应体
                        result.innerHTML = xhr.response;
                    } else {

                    }
                }
            }
        }
    </script>
//post方法发送原生ajax
   <script>
        btn[0].onclick = function(){
            const xhr = new XMLHttpRequest();
            xhr.open('POST', 'http://localhost:8000/server');
            //设置请求头
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xhr.send('a=100&&b=200&&c=300');
            xhr.onreadystatechange = function(){
                if(xhr.readyState === 4){
                    if(xhr.status >= 200 && xhr.status<300){
                        result.innerHTML = xhr.response;
                    }
                }
            };
        };
  </script>
//原生ajax异常处理,在xhr.open()之前
			//超时设置
			xhr.timeout = 2000;
            //超时回调
            xhr.ontimeout = function (){
                alert('网络异常,超时');
            };
            //网络异常回调
            xhr.onerror = function(){
                alert('网络异常');
            };
            //取消请求
        	btns[1].onclick = function(){
            xhr.abort()};

jquery-ajax

在这里插入图片描述

  • 使用前需要引入jquery的相关库
<script>
		//get方式,第四个参数为数据接收类型
        $('button').eq(0).click(function () {
            $.get('http://localhost:8000/jquery-server', { a: 100, b: 200 }, function (data) {
                console.log(data);
            }, 'json')
        });
        //poast方式
        $('button').eq(1).click(function () {
            $.post('http://localhost:8000/jquery-server', { a: 100, b: 200 }, function (data) {
                console.log(data);
            })
        });
        $('button').eq(2).click(function () {
            $.ajax({
                //url
                url: 'http://localhost:8000/jquery-server',
                //参数
                data: { a: 100, b: 200 },
                //请求类型
                type: 'GET',
                //响应体结果
                dataType: 'json',
                //成功的回调
                success: function (data) {
                    console.log(data);
                },
                //超时时间
                timeout: 2000,
                //失败的回调
                error: function () {
                    console.log('出错了');
                },
                //头信息设置
                headers: {
                    c: 300,
                    d: 400
                }
            })
        })
    </script>

axios-ajax

在这里插入图片描述

<script>
        const btns = document.querySelectorAll('button')
        btns[0].onclick = function () {
            //GET请求
            axios.get('http://localhost:8000/axios-server', {
                //url参数
                params: {
                    id: 1000,
                    vip: 10
                },
                //请求头信息
                headers: {
                    name: 'hanser',
                    age: '10'
                }
            }).then(value => {
                console.log(value);
            })
        }
        btns[1].onclick = function () {

            axios.post('http://localhost:8000/axios-server', {
                username: 'admin',
                password: '123'
            }, {
                //url参数
                params: {
                    id: 1,
                    vip: 123
                },
                //请求头参数
                headers: {
                    name: 'younghd',
                    age: '22'
                },
                //请求体
                ...

            })
        }

        btns[2].onclick = function () {
            axios({
                method: 'POST',
                url: 'http://localhost:8000/axios-server',
                //url参数
                params: {
                    vip: 10,
                    id: 123
                },
                //头信息
                headers: {
                    a: 100,
                    b: 200
                },
                //请求体参数
                data: {
                    name: 'younghd',
                    age: '22'
                }
            }).then(response => {
                console.log(response);
            })
        }
    </script>

fetch()-ajax

在这里插入图片描述

<script>
        const btn = document.getElementsByTagName('button');
        btn[0].onclick = function () {
            fetch('http://localhost:8000/fetch-server', {
                //请求方法
                method: 'POST',
                //请求头
                headers: {
                    name: 'YoungHD'
                },
                //请求体
                body: 'name=admin&pd=password'
            }).then(Response => {
                console.log(Response);
                return Response.text();
            }).then(Response => {
                console.log(Response);
            })
        }
    </script>

服务器端:node.js-express

在这里插入图片描述

//1.引入express并创建应用对象
const express = require('express');

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

//3.创建路由规则

//ajax-原生
app.get('/server', (requrest, response)=>{
    //设置响应头 设置允许跨域
    response.setHeader('Access-Control-Allow-Origin', '*')
    //设置响应
    response.send('这是原生ajax');
});

//jquery-ajax
app.all('/jquery-server', (requrest, response)=>{
    //设置允许自定义响应头 设置允许跨域
    response.setHeader('Access-Control-Allow-Origin', '*')
    response.setHeader('Access-Control-Allow-Headers', '*')

    const data = {name:'jquery-ajax'}
    //设置响应
    response.send(JSON.stringify(data))
});

//axios-ajax
app.all('/axios-server', (requrest, response)=>{
    //设置响应头 设置允许跨域
    response.setHeader('Access-Control-Allow-Origin', '*')
    response.setHeader('Access-Control-Allow-Headers', '*')

    const data = {name:'axios-ajax'};
    //设置响应
    response.send(JSON.stringify(data));
});

//fetch-ajax
app.all('/fetch-server', (requrest, response)=>{
    //设置响应头 设置允许跨域
    response.setHeader('Access-Control-Allow-Origin', '*')
    response.setHeader('Access-Control-Allow-Headers', '*')

    const data = {name:'fetch-ajax'};
    //设置响应
    response.send(JSON.stringify(data));
});

//4.监听端口
app.listen(8000,()=>{
    console.log("服务已经启动,8080端口监听响应");
});
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值