Skip to content
Permalink
Browse files

Switched to using new Function instead of eval for handling JSON pars…

…ing (Fixes bug #4680). Added support for JSON.parse, if it exists (Fixes bug #4429).
  • Loading branch information
jeresig committed May 20, 2009
1 parent a0451f1 commit 90a87c03b4943d75c24bc5e6246630231d12d933
Showing with 33 additions and 6 deletions.
  1. +14 −6 src/ajax.js
  2. +19 −0 test/unit/ajax.js
@@ -481,24 +481,32 @@ jQuery.extend({
xml = type == "xml" || !type && ct && ct.indexOf("xml") >= 0,
data = xml ? xhr.responseXML : xhr.responseText;

if ( xml && data.documentElement.tagName == "parsererror" )
if ( xml && data.documentElement.tagName == "parsererror" ) {
throw "parsererror";
}

// Allow a pre-filtering function to sanitize the response
// s != null is checked to keep backwards compatibility
if( s && s.dataFilter )
if ( s && s.dataFilter ) {
data = s.dataFilter( data, type );
}

// The filter can actually parse the response
if( typeof data === "string" ){
if ( typeof data === "string" ) {

// If the type is "script", eval it in global context
if ( type == "script" )
if ( type === "script" ) {
jQuery.globalEval( data );
}

// Get the JavaScript object, if JSON is used.
if ( type == "json" )
data = window["eval"]("(" + data + ")");
if ( type == "json" ) {
if ( typeof JSON === "object" && JSON.parse ) {
data = JSON.parse( data );
} else {
data = (new Function("return " + data))();
}
}
}

return data;
@@ -693,6 +693,25 @@ test("jQuery.getJSON(String, Function) - JSON object", function() {
});
});

test("jQuery.getJSON - Using Native JSON", function() {
expect(2);

var old = window.JSON;
JSON = {
parse: function(str){
ok( true, "Verifying that parse method was run" );
return true;
}
};

stop();
jQuery.getJSON(url("data/json.php"), function(json) {
window.JSON = old;
equals( json, true, "Verifying return value" );
start();
});
});

test("jQuery.getJSON(String, Function) - JSON object with absolute url to local content", function() {
expect(2);

0 comments on commit 90a87c0

Please sign in to comment.
You can’t perform that action at this time.