Skip to content

Commit 787f271

Browse files
rwaldronjeresig
authored andcommitted
Detect JSON Ajax requests by the response content-type (like is done with XML). Fixes jquery#5709.
1 parent 230614b commit 787f271

File tree

3 files changed

+26
-2
lines changed

3 files changed

+26
-2
lines changed

src/ajax.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -557,6 +557,7 @@ jQuery.extend({
557557
httpData: function( xhr, type, s ) {
558558
var ct = xhr.getResponseHeader("content-type"),
559559
xml = type === "xml" || !type && ct && ct.indexOf("xml") >= 0,
560+
json = type === "json" || !type && ct && ct.indexOf("json") >= 0,
560561
data = xml ? xhr.responseXML : xhr.responseText;
561562

562563
if ( xml && data.documentElement.nodeName === "parsererror" ) {
@@ -578,7 +579,7 @@ jQuery.extend({
578579
}
579580

580581
// Get the JavaScript object, if JSON is used.
581-
if ( type === "json" ) {
582+
if ( json ) {
582583
// Try to use the native JSON parser first
583584
try {
584585
data = JSON.parse( data );

test/data/json.php

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,13 @@
11
<?php
22
error_reporting(0);
3+
if ( $_REQUEST['header'] ) {
4+
header("Content-type: application/json");
5+
}
6+
37
$json = $_REQUEST['json'];
48
if($json) {
59
echo '[ {"name": "John", "age": 21}, {"name": "Peter", "age": 25 } ]';
610
} else {
711
echo '{ "data": {"lang": "en", "length": 25} }';
812
}
9-
?>
13+
?>

test/unit/ajax.js

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -797,6 +797,25 @@ test("jQuery.ajax() - script, Remote with scheme-less URL", function() {
797797
});
798798
});
799799

800+
test("jQuery.ajax() - json by content-type", function() {
801+
expect(5);
802+
803+
stop();
804+
805+
jQuery.ajax({
806+
url: "data/json.php",
807+
data: { header: "json", json: "array" },
808+
success: function( json ) {
809+
ok( json.length >= 2, "Check length");
810+
equals( json[0].name, 'John', 'Check JSON: first, name' );
811+
equals( json[0].age, 21, 'Check JSON: first, age' );
812+
equals( json[1].name, 'Peter', 'Check JSON: second, name' );
813+
equals( json[1].age, 25, 'Check JSON: second, age' );
814+
start();
815+
}
816+
});
817+
});
818+
800819
test("jQuery.getJSON(String, Hash, Function) - JSON array", function() {
801820
expect(5);
802821
stop();

0 commit comments

Comments
 (0)