一种不使用 xhr 对象提交 AJAX 请求、内置的、Pormise风格的 使用 AJAX 的方式,但是你不知道也不影响你成为一个合格的前端开发工程师
使用fetch函数发送请求
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>fetch发送AJAX请求</title></head><body><button>AJAX请求</button><script>const btn = document.querySelector("button");btn.onclick = function(){fetch('http://127.0.0.1:8000/fetch-server?vip=10',{//请求方法method:'POST',//请求头headers:{name:'fetchName',},//请求体body:'username=admin&password=admin'}).then(response =>{// console.log(response);// return response.text();return response.json();}).then(response=>{console.log(response);});}</script></body></html>
这里的代码还可以优化许多
类似于这种形式
try {let response = await fetch(url);let data = response.json();console.log(data);} catch(e) {console.log("Oops, error", e);}// 注:这段代码如果想运行,外面需要包一个 async function
上一段代码来自 传统 Ajax 已死,Fetch 永生,15年的文章了,可惜至今仍是 xhr 的天下
server.js
//fetch服务app.all('/fetch-server',(request, response)=>{response.setHeader("Access-Control-Allow-Origin","*");response.setHeader("Access-Control-Allow-Headers","*");const data = {name: 'Axiosdataname',}response.send(JSON.stringify(data));})
使用率不高的原因
- 兼容性:部分老版本浏览器不支持
