JavaScript Fetch API
JavaScript基础 2022-04-25 01:52:5220小码哥的IT人生shichen
JavaScript Fetch API
Fetch API 接口允许 Web 浏览器向 Web 服务器发出 HTTP 请求。
不再需要 XMLHttpRequest。
浏览器支持
表中的数字注明了完全支持 Fetch API 的首个浏览器版本:
Chrome | IE | Firefox | Safari | Opera |
---|---|---|---|---|
Chrome 42 | Edge 14 | Firefox 40 | Safari 10.1 | Opera 29 |
2011 年 6 月 | 2016 年 8 月 | 2015 年 8 月 | 2017 年 3 月 | 2015 年 4 月 |
Fetch API 实例
下面的例子获取文件并显示内容:
示例代码:
fetch(file) .then(x => x.text()) .then(y => myDisplay(y));
完整实例:
<!DOCTYPE html> <html> <body> <p id="demo">获取文件以更改此文本。</p> <script> let file = "/demo/fetch_info.txt" fetch (file) .then(x => x.text()) .then(y => document.getElementById("demo").innerHTML = y); </script> </body> </html>
运行结果:
Fetch API The Fetch API interface allows web browser to make HTTP requests to web servers. If you use the XMLHttpRequest Object, Fetch can do the same in a simpler way.
可以使用本站在线JavaScript测试工具测试上述代码运行效果:http://www.phpcodeweb.com/runjs.html
由于 Fetch 基于 async 和 await,因此上面的例子这么写可能更容易理解:
示例代码:
async function getText(file) { let x = await fetch(file); let y = await x.text(); myDisplay(y); }
完整实例:
<!DOCTYPE html> <html> <body> <p id="demo">获取文件以更改此文本。</p> <script> getText("/demo/fetch_info.txt"); async function getText(file) { let x = await fetch(file); let y = await x.text(); document.getElementById("demo").innerHTML = y; } </script> </body> </html>
运行结果:
Fetch API The Fetch API interface allows web browser to make HTTP requests to web servers. If you use the XMLHttpRequest Object, Fetch can do the same in a simpler way.
可以使用本站在线JavaScript测试工具测试上述代码运行效果:http://www.phpcodeweb.com/runjs.html
甚至可以更好:请使用易于理解的名称而不是 x 和 y:
示例代码:
async function getText(file) { let myObject = await fetch(file); let myText = await myObject.text(); myDisplay(myText); }
完整实例:
<!DOCTYPE html> <html> <body> <p id="demo">获取文件以更改此文本。</p> <script> getText("/demo/fetch_info.txt"); async function getText(file) { let myObject = await fetch(file); let myText = await myObject.text(); document.getElementById("demo").innerHTML = myText; } </script> </body> </html>
运行结果:
Fetch API The Fetch API interface allows web browser to make HTTP requests to web servers. If you use the XMLHttpRequest Object, Fetch can do the same in a simpler way.
可以使用本站在线JavaScript测试工具测试上述代码运行效果:http://www.phpcodeweb.com/runjs.html