使用纯JavaScript设置AJAX内容类型(无JQuery) [英] Set AJAX Content Type with plain JavaScript (No JQuery)

查看:63
本文介绍了使用纯JavaScript设置AJAX内容类型(无JQuery)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm working on form submission with AJAX but using plain JavaScript, no external libraries.

在解析表单时遇到了问题由于PHP似乎无法正确解析数据。

I've been having a problem when it comes to parsing the form as the PHP doesn't seem to be parsing the data correctly.

从互联网上的一些研究中,我已经看到人们将内容类型设置为 false。但是问题是,他们正在使用JQuery来执行此操作,而且我不确定如何在普通JavaScript中执行此操作。

From some research on the internet, I've seen people set the content type to "false". The problem is however, they are are using JQuery to do this and I'm not sure how I do this in plain JavaScript.

我仅提交文件,而我PHP流程表格完美地上传了传统方式。
AJAX似乎也可以正常工作,我看不到代码中的错误。这是我的上传函数。

I am only submitting a file and my PHP processes forms uploaded the traditional way perfectly. The AJAX also seems to work flawlessly and I see no fault in the code. Here is my upload function.

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);


推荐答案

要设置内容类型,您需要修改

In order to set the content type you need to modify the request header.

我不知道您要设置哪种内容类型,所以我默认使用json。

I don't know which content type you'd like to set, so I've defaulted to 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请求标头

这篇关于使用纯JavaScript设置AJAX内容类型(无JQuery)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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