简体   繁体   中英

strange “urlencoded” and “multipart/form-data” content when using ajax jquery

I have the following jQuery script:

<script>
$( document ).ready(function() {

var mydata = "öäüöäü";
$.ajax({
    url : "http://localhost:10000",
    type: "POST",
    data : mydata,
    success: function(data, textStatus, jqXHR) {},
    error: function (jqXHR, textStatus, errorThrown) {}
    })
});
</script>

I'm trying to parse request with Python, what I see on the wire if I run the code above is:

POST / HTTP/1.1\r\n
Host: localhost:10000\r\n
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:34.0) Gecko/20100101 Firefox/34.0\r\n
Accept: */*\r\n
Accept-Language: en-US,en;q=0.5\r\n
Accept-Encoding: gzip, deflate\r\n
Content-Type: application/x-www-form-urlencoded; charset=UTF-8\r\n
Referer: http://localhost/index_ajax.html\r\n
Content-Length: 12\r\n
Origin: http://localhost\r\n
Connection: keep-alive\r\n
Pragma: no-cache\r\n
Cache-Control: no-cache\r\n
\r\n
\xc3\xb6\xc3\xa4\xc3\xbc\xc3\xb6\xc3\xa4\xc3\xbc

Content-Type is "x-www-form-urlencoded" but all the data seems to be byte-encoded and not percent encoded as defined for this content type.

Changing ajax code from:

data : mydata,

to

{'mydata': data}

produces same headers and correct body content:

mydata=%C3%B6%C3%A4%C3%BC%C3%B6%C3%A4%C3%BC

The content is now as expected percent-encoded.

Same body is produced if I add to ajax code another content-type:

contentType:"multipart/form-data"

now I see "Content-Type: multipart/form-data; charset=UTF-8" in headers, but the body itself isn't just as expected for multipart/form-data.

Why does jQuery allow sending non-conform data to server? How do I send correct data to server?

The Content-Type header you see is the default header to be sent. When you set data to a string , jQuery assumes you have taken care of the encoding yourself, for any conversion to take place (eg the form URL encoding) you have to send an object.

See the jQuery.ajax() documentation :

contentType (default: 'application/x-www-form-urlencoded; charset=UTF-8' )

and

data
Type: PlainObject or String or Array
Data to be sent to the server. It is converted to a query string, if not already a string.

Emphasis mine.

If jQuery converted strings, you'd never be able to send valid content types that should not be URL-encoded, like a JSON or XML post body, nor could you post data that was already URL-encoded by other means.

To manually encode data yourself, use the encodeURIComponent() function :

$.ajax({
    url : "http://localhost:10000",
    type: "POST",
    data : encodeURIComponent(mydata),
    success: function(data, textStatus, jqXHR) {},
    error: function (jqXHR, textStatus, errorThrown) {}
    })
});

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