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方式