简体   繁体   中英

JQuery: Wrong form data encoding in AJAX request

I am trying execute this simple AJAX request with JQuery:

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

Of course my backend application doesn't expect such encoding and fails. What is wrong and how to force JQuery to send data in urlencoded format? I tried pass extra headers or contentType options, but nothing works.

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.

u should also add contentType: false

  $.ajax({
        url: "http://localhost:8080/example",
        type: "post",
        data: data,
        processData: false,
        contentType: false,
        success: function (data) {

         }
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM