一:簡單參數
簡單的參數,我們可以使用手動拼接的方式傳遞。
格式為:
fetch(url?key1=val1&key2=val2&...).then((response) => response.json()) .then((json) => { //處理返回值 }).catch((error) => { //異常處理 })
二:POST方法傳遞數據,在fetch方法的參數中定義post方法的參數們:method、headers、body
fetch(url', { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify({ firstParam: 'yourValue', secondParam: 'secondValue', }) })
三:復雜表單數據的傳遞,比如圖片等
我們可以自己new一個FormData,直接傳給body,在FormData中傳遞字節流實現上傳圖片的功能。
let formData = new FormData(); formData.append("key",表單內容); fetch(url , { method: 'POST', headers: {}, body: formData, ).then((response) => { if (response.ok) { return response.json(); } ).then((json) => { alert(JSON.stringify(json)); ).catch((error) => { console.error(error); );