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

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

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

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

**2 问:**FormData使用方法

参考示例:

html 复制代码
<form id="testForm">
    <input name="username" />
</form>

js:

javascript 复制代码
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之外,还需要添加模拟触发下载的代码:

javascript 复制代码
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);
相关推荐
2301_7944615715 小时前
HTML入门
前端·html
Dontla1 天前
Canonical URL介绍(规范网址 / 规范链接)(Canonical Tag 规范标签)HTML标签、SEO优化
前端·html·seo
weixin_439857542 天前
借助AI制作的贪吃蛇游戏(单HTML文件)
游戏·html·ai编程
LaughingZhu3 天前
Product Hunt 每日热榜 | 2026-07-17
前端·数据库·人工智能·经验分享·mysql·chatgpt·html
天若有情6734 天前
纯HTML+Tailwind单页作品集网站——零框架静态前端完整源码
前端·html
qq_419854054 天前
空间网格管理器
前端·javascript·html
天若有情6734 天前
Dev_Portfolio 个人主页html网页源码分享!!!
前端·html·源码·个人主页
云水一下4 天前
零基础玩转 bWAPP 靶场(五):HTML 注入——存储型(博客)
web安全·html·bwapp·存储型注入
芯日记4 天前
Mac-使用文本编辑的html浏览器打开出现源代码问题
macos·html
杨超越luckly4 天前
Agent应用指南:利用POST请求获取麦当劳门店位置信息
人工智能·arcgis·html·数据可视化·麦当劳