why encodeURIComponent() for data in body of POST XHR request? - JavaScript / Ajax / DHTML answers
application/x-www-form-urlencoded
This is the same format as a query string, but the string is passed in the request body rather than the URL.
multipart/form-data
This passes the raw, unescaped data in the the POST body by using a marker to define the data boundaries.
why encodeURIComponent() for data in body of POST XHR request? - JavaScript / Ajax / DHTML answers
Because POST uses the same characters to split ('&' and '=') by default. The method doesn't matter; the data is just offered in another part of the request.
GET looks like this (header):GET /file.html?name=Bart&nr=4 HTTP/1.0
while default POST looks like this (body):
POST /file.html HTTP/1.0
Content-length: 15
name=Bart&nr=4
But the encoding of POST-ed data is only the default behaviour of the browser (which is done in Ajax "by hand" in such libraries).<form method="post">
actually means:<form method="post" enctype="application/x-www-form-urlencoded">
But it's possible to disable this URL-encoding for POST-ed data, mostly to transfer (binary) files to the gateway software. In the following example, you tell the form not to encode anything:<form method="post" enctype="multipart/form-data">
This is the only case where 'é' will be passed as 'é'; under default GET/POST rules it will always be passed as '%E9'.
So as a general conclusion: Ajax libraries must invokeencodeURIComponent()
when sending POST-requests in the "application/x-www-form-urlencoded" encoding type. They must always invokeencodeURIComponent()
for GET. They must not invokeencodeURIComponent()
in the POST "multipart/form-data" type.
Obviously, it also depends on how the gateway software is configured how to handle incoming data (this will be URL decoded by default).
URL-encoding is 'automatic' in browsers as long as you don't override this setting. POST or GET doesn't matter; browser will URL-encode all form values by default before sending them to server.
If you don't want this to happen, you should use
<form method="post" enctype="multipart/form-data">
to receive non-encoded data at server.
沒有留言:
張貼留言