Google returns Unparsable Cuft to the json response like this:
throw 1; <dont be evil> { foo: bar}
- My current web applications use jQuery.Ajax to retrieve JSON data. How should they be modified to consume valid data?
Here is a relevant demo
Google returns Unparsable Cuft to the json response like this:
throw 1; <dont be evil> { foo: bar}
Here is a relevant demo
You should probably remove the beginning part from the response:
$.ajax(url, {
dataType: "jsonp text",
success: function(data) {
var jsonString = data.replace(/^throw 1; <dont be evil> /, "");
var responseObject = $.parseJSON(jsonString);
// do something with responseObject
...
}
}
UPDATE:
To make the re-writing available in every Ajax call you could also register a global Ajax Converter in jQuery:
$.ajaxSetup({
converters: {
"text cleanedjson": function(data) {
var jsonString = data.replace(/^throw 1; <dont be evil> /, "");
return $.parseJSON(jsonString);
}
}
});
$.ajax(url, {
dataType: "jsonp cleanedjson",
success: function(responseObject) {
// do something with responseObject
...
}
});
You will still need to specify your defined dataType
in the request options.
UPDATE 2:
If you need to tweak your existing calls to do the response cleanup automatically, you could patch jQuery's ajax
implementation to automatically use your converter in certain situations:
// store reference to original implementation
$._ajax_original = $.ajax;
// redefine jQuery's ajax function
$.ajax = function(url, settings) {
if (… your test for applicability here (e.g. an url check) …) {
settings.dataType = "jsonp cleanedjson";
}
return $._ajax_original(url, settings);
};
Note that this redefinition has to included after loading jQuery and before the first Ajax call is made. You may also need to consider that $.ajax
can also be called without a separate url
parameter...
I achieved this a little simpler taking advantage of the $.ajaxSetup
method:
http://api.jquery.com/jQuery.ajaxSetup/
and using converters:
$.ajaxSetup({
converters: {
"text json": function (stringData) {
return jQuery.parseJSON(stringData.replace("for(;;);", ""));
}
}
});
What this does is tap into every ajax call and makes the necessary conversion/replacement on the fly. It essentially takes your object which it reads as "text", replaces the unparseable cruft, and spits out a new json object.
Works great. I set it and forget it and it won't interfere with any non-tainted json.