前端异步请求方式

一、XMLHttpRequest,通常简称为XHR

var xhr = new XMLHttpRequest();  
xhr.open("GET", "https://api.example.com/data", true); // 第三个参数表示是否异步  
  
xhr.onreadystatechange = function () {  
    if (xhr.readyState === 4 && xhr.status === 200) {  
        // 请求已完成,且响应已就绪  
        console.log(xhr.responseText); // 打印服务器的响应文本  
    }  
};  
  
xhr.send(); // 发送请求

二、jquery.ajax

$.ajax({  
    url: 'https://api.example.com/data', // 请求的 URL  
    type: 'GET', // 请求的类型(GET、POST 等)  
    dataType: 'json', // 预期服务器返回的数据类型  
    success: function(data, textStatus, jqXHR) {  
        // 请求成功时调用的函数  
        // data 是从服务器返回的数据  
        console.log(data);  
    },  
    error: function(jqXHR, textStatus, errorThrown) {  
        // 请求失败时调用的函数  
        console.error('Error: ' + textStatus, errorThrown);  
    }  
});

三、axios是一个基于Promise的HTTP客户端,用于浏览器和Node.js环境中发起HTTP请求

import axios from 'axios';  

axios.get('/user?ID=12345')  
  .then(function (response) {  
    // 请求成功时处理响应数据  
    console.log(response);  
  })  
  .catch(function (error) {  
    // 请求失败时处理错误  
    console.error(error);  
  });

四、fetch

发送get

fetch('https://api.example.com/data')  
  .then(response => response.json()) // 解析响应为 JSON  
  .then(data => console.log(data)) // 处理解析后的数据  
  .catch(error => console.error('Error:', error)); // 捕获并处理错误

发送post

const data = { key1: 'value1', key2: 'value2' };  
  
fetch('https://api.example.com/submit', {  
  method: 'POST', // 或 'PUT'  
  headers: {  
    'Content-Type': 'application/json',  
  },  
  body: JSON.stringify(data), // 将 JavaScript 对象转换为 JSON 字符串  
})  
.then(response => response.json())  
.then(data => console.log(data))  
.catch(error => console.error('Error:', error));

五、NG HttpClient

import { HttpClientModule } from '@angular/common/http';  
  
@NgModule({  
  imports: [  
    HttpClientModule,  
    // ...  
  ],  
  // ...  
})  
export class AppModule { }




import { HttpClient } from '@angular/common/http';  
  
@Injectable({  
  providedIn: 'root',  
})  
export class DataService {  
  constructor(private http: HttpClient) { }  
  
  fetchData() {  
    return this.http.get('/api/data');  
  }  
}


this.dataService.fetchData().subscribe(  
  data => console.log(data),  
  error => console.error('Error:', error)  
);

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值