关于fetch api这点事
生活随笔
收集整理的這篇文章主要介紹了
关于fetch api这点事
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
fetch
- fetch api
- 文檔地址
- 模擬登錄demo
fetch api
fetch api 是瀏覽器的異步可跨域請求。基于XMLHttpRequest, 也就是對原生Ajax請求的包裝,以回調的形式展開。
使用方法:
fetch('http://example.com/movies.json').then(function(response) {return response.json();}).then(function(myJson) {console.log(myJson);});文檔地址
https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API/Using_Fetch
模擬登錄demo
<!DOCTYPE html> <html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title> </head><body style="width: 100%; height: 100%;"><div><img src="" /><br /><label></label><br /><textarea id="token" style="width: 400px; height: 60px;"></textarea></div><div><form id="loginForm" name="loginForm">code: <input name="code" /> <br />username: <input name="username" /> <br />password: <input name="password" type="password" /> <br />uuid: <input name="uuid" /> <br /><input type="button" onclick="doLogin()" value="login" /></form></div><script>// https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API/Using_Fetchfunction doLogin() {console.log('start login..')let form = document.getElementById("loginForm");console.log(form.code.value)let code = form.code.value;let uuid = form.uuid.value;let username = form.username.value;let password = form.password.value;let data = {uuid, code, username, password }var req = new Request("http://localhost:9999/login")var init = {method: 'POST',mode: 'cors',body: JSON.stringify(data),headers: {'content-type': 'application/json'}}fetch(req, init).then(res => res.json()).then(res => {console.log(res)document.getElementById("token").innerText = res.token;})}var myImage = document.querySelector('img');var myHeaders = new Headers();myHeaders.append('Content-Type', 'image/jpeg');var myInit = {method: 'GET',headers: myHeaders,mode: 'cors',cache: 'default'};// 獲取驗證碼var myRequest = new Request('http://localhost:9999/captchaImage');fetch(myRequest, myInit).then(function (response) {return response;}).then(res => {return res.json();}).then(res => {console.log(res)myImage.src = 'data:image/png;base64,' + res.img;document.querySelector("label").innerText = res.uuid;});</script> </body></html>總結
以上是生活随笔為你收集整理的关于fetch api这点事的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 把docx格式的word文档转换为txt
- 下一篇: js bom and dom