gpt4 book ai didi

javascript - 使用ajax jquery时出现奇怪的 "urlencoded"和 "multipart/form-data"内容

转载 作者:行者123 更新时间:2023-12-03 11:08:06 25 4
gpt4 key购买 nike

我有以下 jQuery 脚本:

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

我正在尝试使用 Python 解析请求,如果运行上面的代码,我在网上看到的是:

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 是“x-www-form-urlencoded”,但所有数据似乎都是字节编码的而不是为此内容类型定义的百分比编码。

更改ajax代码:

data : mydata,

{'mydata': data}

产生相同的标题和正确的正文内容:

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

内容现在按预期进行百分比编码。

如果我向 ajax 代码添加另一个内容类型,则会生成相同的正文:

contentType:"multipart/form-data"

现在我在标题中看到“Content-Type: multipart/form-data; charset=UTF-8”,但正文本身与 multipart/form-data 的预期不同。

为什么 jQuery 允许向服务器发送不符合要求的数据?如何向服务器发送正确的数据?

最佳答案

您看到的 Content-Type header 是要发送的默认 header 。当您将 data 设置为字符串时,jQuery 假定您已自行处理编码,以便进行任何转换(例如表单 URL 编码)必须发送一个对象。

请参阅jQuery.ajax() documentation :

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

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.

强调我的。

如果 jQuery 转换了字符串,您将永远无法发送不应该进行 URL 编码的有效内容类型,例如 JSON 或 XML 帖子正文,也无法发布已经存在的数据通过其他方式进行 URL 编码。

要自己手动编码数据,请使用 encodeURIComponent() function :

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

关于javascript - 使用ajax jquery时出现奇怪的 "urlencoded"和 "multipart/form-data"内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27749113/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com