jQuery:AJAX请求中的表单数据编码错误

我正在尝试使用JQuery执行此简单的AJAX请求:

const data = new FormData();
data.append("foo", "bar");
$.ajax({
    url: "http://localhost:8080/example",
    type: "post",
    data: data,
    processData: false
});

I check request by Google Chrome developer tools. I see that Content-type is application/x-www-form-urlencoded; charset=UTF-8 which is expected, but actual data sent in multipart encoding:

------WebKitFormBoundaryEzaaFpNlUo3QpKe1
Content-Disposition: form-data; name: "foo"

bar
------WebKitFormBoundaryEzaaFpNlUo3QpKe1--

当然,我的后端应用程序不希望这样的编码并失败。有什么问题,以及如何强制JQuery以urlencoded格式发送数据?我尝试传递额外的标题或contentType选项,但没有任何效果。

评论
  • yquo
    yquo 回复

    FormData is always sent as multipart/form-data. It's usually used when you're uploading a file or blob, which can't be URL-encoded.

    If you want URL-encoded, don't use FormData. Use a regular object, and jQuery will encode it properly.

    const data = {foo: "bar"};
    

    Also, don't use processData: false when you're doing this.