ad
07月02 21:22 PM,2025年

小白新手学习认识什么是Ajax异步请求

Ajax(Asynchronous JavaScript and XML)是一种在无需重新加载整个页面的情况下,能够更新部分网页的技术。它通过在后台与服务器交换数据,并使用JavaScript动态更新网页的技术。Ajax 技术依赖于一系列的Web技术,包括:
XMLHttpRequest 对象(用于在后台与服务器交换数据)
JavaScript 和 DOM 方法(用于在页面上显示或使用从服务器接收的数据)

//JavaScript写法
var xhr = new XMLHttpRequest();
var url = "https://api.domain.com/data";
xhr.open('GET', url, true);
 
xhr.onreadystatechange = function () {
    if (xhr.readyState == 4 && xhr.status == 200) {
        // 请求成功,处理返回的数据
        console.log(xhr.responseText);
    }
};
 
xhr.send();


//jquery封装写法 get
$.get(url,function(res){
    
    if(res.code==200){
        console.log(res.data);
    }
});

// post
$.post(url,{id:11},function(res){
    
    if(res.code==200){
        console.log(res.data);
    }
});

// 写法有很多,看个人习惯
$.ajax({
    url:url,
    data:{id:99},
    method:"POST",
}).done(function(res){
    console.log(res);
})

基于 Fetch Api

//代码如下
var url = "https://api.domain.com/data";
fetch(url)
    .then(response => response.json()) // 将响应解析为JSON格式
    .then(data => {
        // 处理数据
        console.log(data);
    })
    .catch(error => {
        // 处理错误
        console.error('Error:', error);
    });

使用 Axios(基于 Promise 的 HTTP 客户端)

//代码如下
import axios from 'axios';
var url = "https://domain.com/data"
axios.get(url)
    .then(response => {
        // 处理返回的数据
        console.log(response.data);
    })
    .catch(error => {
        // 处理错误
        console.error('Error:', error);
    });

类目

0 评论

暂无评论~

发表评论

ad
back top