Skip to content

Commit 88937d5

Browse files
author
Brad Greenlee
committed
Make an attempt to parse the response body as XML if the user is expecting XML, even if the Content-Type says otherwise.
Prior to this patch, if an XML document is sent with the wrong Content-Type (e.g. "text/html"), jQuery will return a parsererror, even if the response body is valid XML. This issue was discovered via a Rails bug in which cached content (in our case, an XML document) is returned with a Content-Type of "text/html" rather than the original Content-Type. See https://rails.lighthouseapp.com/projects/8994/tickets/1585-action-caching-sets-wrong-content-type-when-cache_path-is-a-string Ticket #5764 (http://dev.jquery.com/ticket/5764)
1 parent ff3645e commit 88937d5

File tree

3 files changed

+37
-0
lines changed

3 files changed

+37
-0
lines changed

src/ajax.js

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -558,6 +558,17 @@ jQuery.extend({
558558
var ct = xhr.getResponseHeader("content-type"),
559559
xml = type === "xml" || !type && ct && ct.indexOf("xml") >= 0,
560560
data = xml ? xhr.responseXML : xhr.responseText;
561+
562+
// if we're expecting xml and the content-type is wrong, try to parse the responseText
563+
if (xml && !(data && data.documentElement)) {
564+
if (window.DOMParser)
565+
data = new DOMParser().parseFromString(xhr.responseText, "text/xml");
566+
else { // IE
567+
data = new ActiveXObject("Microsoft.XMLDOM");
568+
data.async = "false";
569+
data.loadXML(xhr.responseText);
570+
}
571+
}
561572

562573
if ( xml && data.documentElement.nodeName === "parsererror" ) {
563574
throw "parsererror";

test/data/xml_as_html.php

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
<?php
2+
header("Content-Type: text/html");
3+
echo '<?xml version="1.0" encoding="UTF-8"?>';
4+
?>
5+
<root>
6+
<nodes>
7+
<node>Peanut Butter</node>
8+
<node>Jelly</node>
9+
</nodes>
10+
</root>

test/unit/ajax.js

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1065,6 +1065,22 @@ test("jQuery.ajax - Etag support", function() {
10651065
});
10661066
});
10671067

1068+
test("jQuery.ajax - XML with wrong Content-Type", function() {
1069+
expect(1);
1070+
stop();
1071+
jQuery.ajax({
1072+
url: "data/xml_as_html.php",
1073+
dataType: "xml",
1074+
success: function(data) {
1075+
equals( jQuery("node", data).length, 2, 'nodes in responseXML' );
1076+
start();
1077+
},
1078+
error: function(data, status) {
1079+
ok(false, "failed with status: " + status);
1080+
start();
1081+
}
1082+
});
1083+
});
10681084
}
10691085

10701086
//}

0 commit comments

Comments
 (0)