利用fetch替代ajax请求的具体实现

本文介绍了如何使用fetch API来替代传统的ajax请求方式,包括fetch的使用示例以及如何结合async、await进行异步操作。同时,为了确保兼容性,提供了检查浏览器是否支持fetch的方案,如果不支持则回退到使用Promise处理ajax请求。

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

传统的ajax写法:

var xhr = new XMLHttpRequest(); 
xhr.open("GET", url); 
xhr.responseType = 'json'; 
xhr.onload = function(){ 
 console.log(xhr.response); 
}; 
xhr.onerror = function(){ 
 console.log("error") 
} 
xhr.send();

fetch写法:

fetch(url).then(function(response){
   return response.json()
}).then(function(data){
   console.log(data)
}).catch(function(err){
   console.log(err)
})

利用async、await

try{
  let response = fetch(url);
  let data = await response.json();
  return data;
} catch (err){
  console.log(err)
}

fetch api 点击这里

兼容ajax 和 fetch的实现:判断浏览器是否支持 fetch 不支持则利用 promise 返回

let baseUrl = 'localhost:8088'

export default async(url = '', data = {}, type = 'GET', method = 'fetch') => {
	type = type.toUpperCase();
	url = baseUrl + url;

	if (type == 'GET') {
		let dataStr = ''; 
		Object.keys(data).forEach(key => {
			dataStr += key + '=' + data[key] + '&';
		})

		if (dataStr !== '') {
			dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
			url = url + '?' + dataStr;
		}
	}

	if (window.fetch && method == 'fetch') {
		let requestConfig = {
			credentials: 'include',
			method: type,
			headers: {
				'Accept': 'application/json',
				'Content-Type': 'application/json'
			},
			mode: "cors",
			cache: "force-cache"
		}

		if (type == 'POST') {
			Object.defineProperty(requestConfig, 'body', {
				value: JSON.stringify(data)
			})
		}
		
		try {
			const response = await fetch(url, requestConfig);
			const responseJson = await response.json();
			return responseJson
		} catch (error) {
			throw new Error(error)
		}
	} else {
		return new Promise((resolve, reject) => {
			let requestObj;
			if (window.XMLHttpRequest) {
				requestObj = new XMLHttpRequest();
			} else {
				requestObj = new ActiveXObject;
			}

			let sendData = '';
			if (type == 'POST') {
				sendData = JSON.stringify(data);
			}

			requestObj.open(type, url, true);
			requestObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			requestObj.send(sendData);

			requestObj.onreadystatechange = () => {
				if (requestObj.readyState == 4) {
					if (requestObj.status == 200) {
						let obj = requestObj.response
						if (typeof obj !== 'object') {
							obj = JSON.parse(obj);
						}
						resolve(obj)
					} else {
						reject(requestObj)
					}
				}
			}
		})
	}
}

具体使用方法:

const url = '/login'

const login = data => fetch(url, data, 'post')

const res = await login({name: 'admin', password: '123456'});

console.log(res)


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值