目录结构:
读取文本数据
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script> window.onload = function() { let obtn = document.getElementById('btn1') obtn.onclick = async function() { // 1.请求 let res = await fetch('data/1.txt') // 2.解析文本数据 let data = await res.text() console.log(data) } } </script> </head> <body> <input type="button" value="读取" id="btn1"> </body> </html>
读取json数据
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script> window.onload = function() { let obtn = document.getElementById('btn1') obtn.onclick = async function() { // 1.请求 let res = await fetch('data/1.json') // 2.解析json数据 let data = await res.json() console.log(data) } } </script> </head> <body> <input type="button" value="读取" id="btn1"> </body> </html>
读取二进制数据
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script> window.onload = function() { let obtn = document.getElementById('btn1') let oImg = document.getElementById('img1') obtn.onclick = async function() { // 1.请求 let res = await fetch('data/123.jpg') // 2.解析 图片 数据 let data = await res.blob(); let url = URL.createObjectURL(data); console.log(url) // blob:http://localhost/af62b20b-7964-47ab-8fd3-a40f4de2d5f8 oImg.src = url; } } </script> </head> <body> <input type="button" value="读取" id="btn1"> <img id="img1" /> </body> </html>