Skip to content

Commit

Permalink
Make an attempt to parse the response body as XML if the user is expe…
Browse files Browse the repository at this point in the history
…cting 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)
  • Loading branch information
Brad Greenlee committed Jan 6, 2010
1 parent ff3645e commit 88937d5
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 0 deletions.
11 changes: 11 additions & 0 deletions src/ajax.js
Original file line number Diff line number Diff line change
Expand Up @@ -558,6 +558,17 @@ jQuery.extend({
var ct = xhr.getResponseHeader("content-type"),
xml = type === "xml" || !type && ct && ct.indexOf("xml") >= 0,
data = xml ? xhr.responseXML : xhr.responseText;

// if we're expecting xml and the content-type is wrong, try to parse the responseText
if (xml && !(data && data.documentElement)) {
if (window.DOMParser)
data = new DOMParser().parseFromString(xhr.responseText, "text/xml");
else { // IE
data = new ActiveXObject("Microsoft.XMLDOM");
data.async = "false";
data.loadXML(xhr.responseText);
}
}

if ( xml && data.documentElement.nodeName === "parsererror" ) {
throw "parsererror";
Expand Down
10 changes: 10 additions & 0 deletions test/data/xml_as_html.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php
header("Content-Type: text/html");
echo '<?xml version="1.0" encoding="UTF-8"?>';
?>
<root>
<nodes>
<node>Peanut Butter</node>
<node>Jelly</node>
</nodes>
</root>
16 changes: 16 additions & 0 deletions test/unit/ajax.js
Original file line number Diff line number Diff line change
Expand Up @@ -1065,6 +1065,22 @@ test("jQuery.ajax - Etag support", function() {
});
});

test("jQuery.ajax - XML with wrong Content-Type", function() {
expect(1);
stop();
jQuery.ajax({
url: "data/xml_as_html.php",
dataType: "xml",
success: function(data) {
equals( jQuery("node", data).length, 2, 'nodes in responseXML' );
start();
},
error: function(data, status) {
ok(false, "failed with status: " + status);
start();
}
});
});
}

//}

0 comments on commit 88937d5

Please sign in to comment.