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);
相关推荐
veminhe9 天前
HTML5 浏览器支持
前端·html·html5
訾博ZiBo9 天前
开源分享:我开发了一个智能文本提取浏览器插件,彻底解决复制粘贴的烦恼
前端·react.js·html
A5资源网9 天前
为WordPress 网站创建一个纯文本网站地图(Sitemap)
前端·数据仓库·html·php
伍哥的传说10 天前
Node.js爬虫 CheerioJS ‌轻量级解析、操作和渲染HTML及XML文档
爬虫·node.js·html
gavin_gxh10 天前
倒计时 效果
前端·css·html
白话10 天前
Vue2批量生成二维码并下载
javascript·html
颜漠笑年10 天前
看看DeepSeek是如何实现前端日历组件的?
前端·html·代码规范
veminhe10 天前
HTML5简介
前端·html·html5
fs哆哆11 天前
在VB.net中,文本插入的几个自定义函数
服务器·前端·javascript·html·.net
动能小子ohhh11 天前
html实现登录与注册功能案例(不写死且只使用js)
开发语言·前端·javascript·python·html