fetch請求
提交圖片,只支持formData方式,這樣會自動變為multiform方式,而且一般的post大多都可以用這樣的方式來完成請求
const formData = new FormData();
formData.append('file', fileInput.files[0]);
formData.append('pid', id);
formData.append('dc', 1);fetch('/api/common/upload', {method: 'POST',body: formData,
})
.then(response => response.json())
.then(data => {console.log('Success:', data);
})
.catch((error) => {console.error('Error:', error);
});
另外一種方式用json方式請求,大多數情況下,請求也都可以用這種方式
fetch('/htgl.php/s/order/update_img?_ajax=1', {method: 'POST',headers: {'Content-Type': 'application/json', // 設置請求頭為 JSON 格式},body: JSON.stringify({id: id, imgurl: data.data.fullurl}),}).then(response => response.json()).then(data => {console.log('Success:', data);$('#imgurl_src_' + id).attr('src', data.data.url);Toastr.success('更新圖片成功');}).catch((error) => {Toastr.error(error || error.msg() || '請求失敗,請檢查網絡');console.error('Error:', error);}).finally(() => {Layer.closeAll('loading');Toastr.success('上傳成功');});
但是formData方式更靈活,不需要手動設置請求頭,任何場景都適用,json則只支持一般數據,不支持文件和普通文本等特殊情況,建議使用formData方式