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);
相关推荐
软件技术NINI22 分钟前
html css js网页制作成品——HTML+CSS甜品店网页设计(4页)附源码
javascript·css·html
NoneCoder4 小时前
HTML响应式网页设计与跨平台适配
前端·html
xcLeigh10 小时前
HTML5好看的水果蔬菜在线商城网站源码系列模板7
前端·html·html5
非凡网站11 小时前
企业网站html源代码 企业网站管理源码模板
前端·html
一个天蝎座 白勺 程序猿11 小时前
Python爬虫(3)HTML核心技巧:从零掌握class与id选择器,精准定位网页元素
前端·爬虫·html
wuhen_n1 天前
CSS元素动画篇:基于当前位置的变换动画(一)
前端·css·html·css3·html5
一只小风华~1 天前
Web前端开发:CSS Float(浮动)与 Positioning(定位)
前端·css·html·html5·web
听风吹等浪起1 天前
html5:从零构建经典游戏-扫雷游戏
前端·html·html5