Permalink
Browse files

Enable changing Ajax settings in `beforeSend` callback

Previously one could only affect these settings:
- `timeout`
- POST `data` (as an already serialized string)

Now you can affect these settings as well:
- `url`
- `type`
- `headers`

However you still can't manipulate `data` as a hash even if it was
originally passed as one. This is by design and for jQuery
compatibility.

Fixes #499
  • Loading branch information...
mislav committed Nov 26, 2013
1 parent d5c4f5a commit 23d1879d55e89b4a375aaa1aefd71ff2582deabc
Showing with 48 additions and 5 deletions.
  1. +5 −5 src/ajax.js
  2. +43 −0 test/ajax.html
View
@@ -231,16 +231,16 @@
}
}
- var async = 'async' in settings ? settings.async : true
- xhr.open(settings.type, settings.url, async)
-
- for (name in settings.headers) xhr.setRequestHeader(name, settings.headers[name])
-
if (ajaxBeforeSend(xhr, settings) === false) {
xhr.abort()
return false
}
+ var async = 'async' in settings ? settings.async : true
+ xhr.open(settings.type, settings.url, async)
+
+ for (name in settings.headers) xhr.setRequestHeader(name, settings.headers[name])
+
if (settings.timeout > 0) abortTimeout = setTimeout(function(){
xhr.onreadystatechange = empty
xhr.abort()
View
@@ -973,6 +973,49 @@ <h1>Zepto Ajax unit tests</h1>
t.assertEqual(MockXHR.last, xhr)
},
+ testBeforeSendCanChangeUrl: function(t) {
+ var xhr = $.ajax({
+ url: 'one',
+ beforeSend: function(x, s) {
+ s.url = 'two'
+ }
+ })
+ t.assertEqual('two', xhr.url)
+ },
+
+ testBeforeSendCanChangeMethod: function(t) {
+ var xhr = $.ajax({
+ type: 'POST',
+ beforeSend: function(x, s) {
+ s.type = 'PUT'
+ }
+ })
+ t.assertEqual('PUT', xhr.method)
+ },
+
+ testBeforeSendCanAccessSerializedData: function(t) {
+ var xhr = $.ajax({
+ data: { a:'b' },
+ beforeSend: function(x, s) {
+ s.data = s.data.toUpperCase()
+ }
+ })
+ t.assertEqual('A=B', xhr.data)
+ },
+
+ testBeforeSendCanChangeAndAddHeaders: function(t) {
+ var xhr = $.ajax({
+ headers: { a:'b', c:'d' },
+ beforeSend: function(x, s) {
+ s.headers['a'] = 'B'
+ s.headers['e'] = 'f'
+ }
+ })
+ t.assert(xhr.headers.some(matchHeader('a', 'B')))
+ t.assert(xhr.headers.some(matchHeader('c', 'd')))
+ t.assert(xhr.headers.some(matchHeader('e', 'f')))
+ },
+
testBeforeSendAbortCallback: function(t) {
var xhr, beforeFired = false, settings = {}
$.ajax({

0 comments on commit 23d1879

Please sign in to comment.