簡體   English   中英

使用ajax jquery時出現奇怪的“ urlencoded”和“ multipart / form-data”內容

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

我有以下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標頭是要發送的默認標頭。 當您將data設置為字符串時 ,jQuery假定您已經自己進行了編碼,要進行任何轉換(例如,格式URL編碼),您必須發送一個對象。

請參閱jQuery.ajax()文檔

contentType (預設值: 'application/x-www-form-urlencoded; charset=UTF-8'

數據
類型: PlainObjectStringArray
數據要發送到服務器。 如果還不是字符串,則將其轉換為查詢字符串。

強調我的。

如果jQuery的轉換字符串,你永遠無法發送應該是URL編碼,就像一個JSON或XML后身體有效的內容類型,也不是你可以張貼已經URL編碼通過其他方式的數據。

要自己手動編碼數據,請使用encodeURIComponent()函數

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM