Monday, August 17, 2009

Using JQuery's dataFilter option to plugin parser for json

In a JQuery ajax call, when the data type is set to "json", JQuery uses the "eval" function to convert the response from the server into a valid Json object. There are some security concerns with using eval. As mentioned in the post, the alternative to using eval is to use a json parser. The downside is that javascript parsers are not going to be as performant as using eval. An easy way to plugin your parser is to use the dataFilter option in JQuery ajax call. For example:

$.ajax({
type: method,
url: url,
data: data,
dataFilter: function(data) { <<<<<<<<
return jsonParse(data);
},
timeout: 20000,
cache: false,
success: success,
error: error
});
Notice the dataType parameter is omitted since we handle the parsing ourself.