form表单提交前设置请求头request header及文件下载

发布于:2025-05-01 ⋅ 阅读:(23) ⋅ 点赞:(0)

需求:想要在form表单submit之前,设置一下请求头。

除了用Ajax发起请求之外,还可以使用FormData来实现,咱不懂就问。

1 问:FormData什么时间出现的?与ajax什么联系?

2 问:FormData使用方法

参考示例:

<form id="testForm">
    <input name="username" />
</form>

js:

let data= new FormData(document.getElementById('testForm'));
let xhrObj = new XMLHttpRequest();
xhrObj.open('POST', url, true);
xhrObj.setRequestHeader('自定义请求头', '值');
xhrObj.onload = function () {
    if (xhrObj.readyState === 4 && xhrObj.status === 200) {
        console.log(xhrObj.responseText);
    } else {
        // 请求错误
    }
};
xhrObj.send(data);

如果请求是一个下载文件(二进制流)的url,除了需要额外设置下responseType之外,还需要添加模拟触发下载的代码:

let data= new FormData(document.getElementById('testForm'));
let xhrObj = new XMLHttpRequest();
xhrObj.open('POST', downloadUrl, true);
xhrObj.setRequestHeader('自定义请求头', '值');
xhrObj.responseType = 'blob';
xhrObj.onload = function () {
    if (xhrObj.readyState === 4 && xhrObj.status === 200) {
		let content= xhrObj.getResponseHeader('Content-Disposition');
		let fileName = content.split(';')[1];
		fileName = decodeURI(fileName.split('=')[1]);
		let respObj= xhrObj.response;
		let downloadLink = document.createElement('a');
		downloadLink.href = URL.createObjectURL(respObj);
		downloadLink.download = fileName;
		downloadLink.click();
    } else {
        // 请求错误
    }
};
xhrObj.send(data);


网站公告

今日签到

点亮在社区的每一天
去签到