From 065143c2e93512eb0c82d1b344b71d06eb7cf01c Mon Sep 17 00:00:00 2001 From: Christian Wenz Date: Mon, 6 Apr 2020 21:15:55 +0200 Subject: [PATCH] Ajax: Overwrite s.contentType with content-type header value, if any MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit This fixes the issue of "%20" in POST data being replaced with "+" even for requests with content-type different from "application/x-www-form-urlencoded", e.g. for "application/json". Fixes gh-4119 Closes gh-4650 (cherry picked from 7fb90a6beaeffe16699800f73746748f6a5cc2de) Co-authored-by: Richard Gibson Co-authored-by: Michał Gołębiowski-Owczarek --- src/ajax.js | 9 +++++++++ test/unit/ajax.js | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+) diff --git a/src/ajax.js b/src/ajax.js index 639a6a380..7e8f552aa 100644 --- a/src/ajax.js +++ b/src/ajax.js @@ -855,5 +855,14 @@ jQuery.each( [ "get", "post" ], function( _i, method ) { }; } ); +jQuery.ajaxPrefilter( function( s ) { + var i; + for ( i in s.headers ) { + if ( i.toLowerCase() === "content-type" ) { + s.contentType = s.headers[ i ] || ""; + } + } +} ); + return jQuery; } ); diff --git a/test/unit/ajax.js b/test/unit/ajax.js index b91ef6711..d9b984799 100644 --- a/test/unit/ajax.js +++ b/test/unit/ajax.js @@ -1326,6 +1326,52 @@ QUnit.module( "ajax", { }; } ); + ajaxTest( "jQuery.ajax() - don't escape %20 with contentType override (gh-4119)", 1, function( assert ) { + return { + url: "bogus.html", + contentType: "application/x-www-form-urlencoded", + headers: { "content-type": "application/json" }, + method: "post", + dataType: "json", + data: "{\"val\":\"%20\"}", + beforeSend: function( _, s ) { + assert.strictEqual( s.data, "{\"val\":\"%20\"}", "data is not %20-encoded" ); + return false; + }, + error: true + }; + } ); + + ajaxTest( "jQuery.ajax() - escape %20 with contentType override (gh-4119)", 1, function( assert ) { + return { + url: "bogus.html", + contentType: "application/json", + headers: { "content-type": "application/x-www-form-urlencoded" }, + method: "post", + dataType: "json", + data: "{\"val\":\"%20\"}", + beforeSend: function( _, s ) { + assert.strictEqual( s.data, "{\"val\":\"+\"}", "data is %20-encoded" ); + return false; + }, + error: true + }; + } ); + + ajaxTest( "jQuery.ajax() - override contentType with header (gh-4119)", 1, function( assert ) { + return { + url: "bogus.html", + contentType: "application/json", + headers: { "content-type": "application/x-www-form-urlencoded" }, + beforeSend: function( _, s ) { + assert.strictEqual( s.contentType, "application/x-www-form-urlencoded", + "contentType is overwritten" ); + return false; + }, + error: true + }; + } ); + ajaxTest( "jQuery.ajax() - data - no processing POST", 1, function( assert ) { return { url: "bogus.html", -- 2.39.5