发送带有标头和FormData的XMLHttpRequest [英] Send XMLHttpRequest with both Header and FormData

查看:277
本文介绍了发送带有标头和FormData的XMLHttpRequest的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试发送带有标头的XMLHttpRequest并添加FormData.有没有一种(优雅的)方式我可以做这样的事情:

I am trying to send a XMLHttpRequest with a header and add a FormData. Is there an (elegant) way i can do something like this:

var formData = new FormData();
formData.append("file", file);
var xhr = new XMLHttpRequest();

xhr.open("POST", "/ajax_gateway.php?mod=fileupload", true);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded")
xhr.send(formData, "token=add");

推荐答案

发送FormData时不能指定Content-Type头,因为浏览器会自动将该头设置为"multipart/form-data".您也可以设置其他标题,请尝试以下操作:

You cannot specify the Content-Type header when sending FormData because that header automatically gets set to "multipart/form-data" by the browser. You can set other headers though, try this:

var formData = new FormData();
formData.append("file", file);
formData.append("mod", "fileupload");
formData.append("token", "add");

var xhr = new XMLHttpRequest();
xhr.open("POST", "/ajax_gateway.php");
xhr.setRequestHeader("X-Answer", "42");
xhr.send(formData);

这篇关于发送带有标头和FormData的XMLHttpRequest的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆