Skip to content

Commit

Permalink
added data filter option
Browse files Browse the repository at this point in the history
  • Loading branch information
Harkaran committed Jul 7, 2016
1 parent 7098d13 commit 6f8aa41
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 1 deletion.
14 changes: 13 additions & 1 deletion src/ajax.js
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,12 @@
ajaxStop(settings)
}

function ajaxDataFilter(data, type, settings) {
if (settings.dataFilter == empty) return data
var context = settings.context
return settings.dataFilter.call(context, data, type)
}

// Empty function, used as default callback
function empty() {}

Expand Down Expand Up @@ -161,7 +167,11 @@
// Whether data should be serialized to string
processData: true,
// Whether the browser should be allowed to cache GET responses
cache: true
cache: true,
//Used to handle the raw response data of XMLHttpRequest.
//This is a pre-filtering function to sanitize the response.
//The sanitized response should be returned
dataFilter: empty
}

function mimeToDataType(mime) {
Expand Down Expand Up @@ -258,6 +268,8 @@

try {
// http://perfectionkills.com/global-eval-what-are-the-options/
// sanitize response accordingly if data filter callback provided
result = ajaxDataFilter(result, dataType, settings)
if (dataType == 'script') (1,eval)(result)
else if (dataType == 'xml') result = xhr.responseXML
else if (dataType == 'json') result = blankRE.test(result) ? null : $.parseJSON(result)
Expand Down
17 changes: 17 additions & 0 deletions test/ajax.html
Original file line number Diff line number Diff line change
Expand Up @@ -322,6 +322,23 @@ <h1>Zepto Ajax unit tests</h1>
})
},

testAjaxDataFilterJSON: function(t){
t.pause()
resumeOnAjaxError(t)

$.ajax({
url: 'taintedJSON',
dataFilter: function(data, type) {
if (!data) return
return data.replace(/^\s*while\(1\);\s*/, '')
},
headers: { accept: 'application/json' },
success: t.reg.resumeHandler('success', function(data){
t.assertEqual('world', data.hello)
})
})
},

testAjaxGetJSON: function(t){
t.pause()
resumeOnAjaxError(t)
Expand Down
4 changes: 4 additions & 0 deletions test/server.coffee
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,10 @@ app.get '/test/json', (req, res) ->
else
res.send 400, 'FAIL'

app.get '/test/taintedJSON', (req, res) ->
res.set 'Content-Type', 'application/json'
res.send 'while(1);{"hello" : "world"}'

app.post '/test/create', (req, res) ->
res.json
action: 'created'
Expand Down

0 comments on commit 6f8aa41

Please sign in to comment.