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

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值