fetch请求总结,fastadmin中后台接口强制返回json数据

fetch请求

提交图片,只支持formData方式,这样会自动变为multiform方式,而且一般的post大多都可以用这样的方式来完成请求

javascript 复制代码
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方式请求,大多数情况下,请求也都可以用这种方式

javascript 复制代码
                            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方式

fastadmin中后台接口强制返回json数据只需要url后面跟上?_ajax=1即可

相关推荐
phantom_11111 小时前
Jsoniter Unmarshal类型错误的友好提示
json
2501_903238651 天前
PrimeFaces Poll组件实现周期性Ajax调用
前端·ajax·okhttp·个人开发
Ronin-Lotus1 天前
嵌入式硬件篇---OpenMV串口通信&json字符串
python·嵌入式硬件·json·uart·openmv
A__tao2 天前
在线SQL转JSON-GO在线工具集
数据库·sql·json
一晌小贪欢3 天前
Python办公笔记——将csv文件转Json
笔记·python·json·python办公·python读取csv
另寻沧海4 天前
如何打开vscode系统用户全局配置的settings.json
ide·vscode·json
leo_hush4 天前
java解析复杂json
java·前端·json
脚大江山稳5 天前
JSON常用的工具方法
java·json·糊涂工具
大美B端工场-B端系统美颜师6 天前
站在JavaScript的视角去看,HTML的DOM和GLTF的Json数据。
javascript·html·json·gltf