使用纯JavaScript设置AJAX内容类型(无JQuery)


Set AJAX Content Type with plain JavaScript (No JQuery)

我使用AJAX进行表单提交,但使用纯JavaScript,没有外部库。

我在解析表单时遇到了一个问题,因为PHP似乎没有正确解析数据。

从互联网上的一些研究中,我看到人们将内容类型设置为"虚假"。然而,问题是,他们正在使用JQuery来实现这一点,我不确定我是如何在纯JavaScript中实现这一目标的。

我只提交了一个文件,我的PHP完美地处理了传统方式上传的表单。AJAX似乎也能完美地工作,我在代码中没有看到任何错误。这是我的上传功能。

var fd = new FormData();
fd.append("upload-file", document.getElementById('upload-file').files[0]);
var xhr = new XMLHttpRequest();
/* I add some event listeners here for progress, load, error, and abort */
xhr.open("POST", "upload.php");
xhr.send(fd);

为了设置内容类型,您需要修改请求标头。

我不知道你想设置哪种内容类型,所以我默认为json。

以下是设置方法:

var fd = new FormData();
fd.append("upload-file", document.getElementById('upload-file').files[0]);
var xhr = new XMLHttpRequest();
/* I add some event listeners here for progress, load, error, and abort */
xhr.open("POST", "upload.php");
xhr.setRequestHeader("Content-type","application/json");
xhr.send(fd);

编辑:从MDN 设置HTTP请求标头