0
# jQuery Compatibility
1
2
Configuration utilities and jQuery/Zepto compatibility layer for seamless migration from other AJAX libraries. Provides global defaults configuration and option remapping to handle differences between reqwest and jQuery/Zepto APIs.
3
4
## Capabilities
5
6
### Ajax Setup
7
8
Sets global default options that will be applied to all subsequent requests.
9
10
```javascript { .api }
11
/**
12
* Sets global default options for all requests
13
* @param {Object} options - Global configuration options
14
*/
15
reqwest.ajaxSetup(options);
16
17
interface GlobalOptions {
18
dataFilter?: Function; // Global response filtering function
19
// Any other reqwest option can be set as global default
20
}
21
```
22
23
**Usage Examples:**
24
25
```javascript
26
// Set global data filter
27
reqwest.ajaxSetup({
28
dataFilter: function(data, type) {
29
// Remove security prefix from all JSON responses
30
if (type === 'json' && typeof data === 'string') {
31
return data.replace(/^\)\]\}',?\n/, '');
32
}
33
return data;
34
}
35
});
36
37
// Set global headers
38
reqwest.ajaxSetup({
39
headers: {
40
'X-Requested-With': 'XMLHttpRequest',
41
'Authorization': 'Bearer ' + getAuthToken()
42
}
43
});
44
45
// Set global timeout
46
reqwest.ajaxSetup({
47
timeout: 30000, // 30 seconds for all requests
48
error: function(xhr, type, error) {
49
if (type === 'timeout') {
50
console.log('Request timed out - check your connection');
51
}
52
}
53
});
54
55
// Multiple configurations
56
reqwest.ajaxSetup({
57
contentType: 'application/json',
58
processData: false,
59
dataFilter: function(data, type) {
60
// Log all responses for debugging
61
console.log('Response received:', type, data);
62
return data;
63
},
64
before: function(xhr) {
65
// Add timestamp to all requests
66
xhr.setRequestHeader('X-Request-Time', new Date().toISOString());
67
}
68
});
69
```
70
71
### Compatibility Mode
72
73
jQuery/Zepto compatibility layer that remaps option names to handle API differences.
74
75
```javascript { .api }
76
/**
77
* jQuery/Zepto compatibility layer
78
* @param {Object} options - jQuery-style options object
79
* @param {Function} callback - Optional success callback
80
* @returns {Object} Request object with promise-like interface
81
*/
82
reqwest.compat(options, callback);
83
```
84
85
**Option Remapping:**
86
- `type` (jQuery) → `method` (reqwest)
87
- `dataType` (jQuery) → `type` (reqwest)
88
- `jsonp` (jQuery) → `jsonpCallback` (reqwest)
89
- `jsonpCallback` (jQuery) → `jsonpCallbackName` (reqwest)
90
91
**Usage Examples:**
92
93
```javascript
94
// jQuery-style options
95
reqwest.compat({
96
url: '/api/data',
97
type: 'POST', // Mapped to method: 'POST'
98
dataType: 'json', // Mapped to type: 'json'
99
data: { name: 'John' },
100
success: function(data) {
101
console.log('Success:', data);
102
},
103
error: function(xhr, status, error) {
104
console.log('Error:', error);
105
}
106
});
107
108
// JSONP with jQuery-style options
109
reqwest.compat({
110
url: 'https://api.example.com/data',
111
dataType: 'jsonp', // Mapped to type: 'jsonp'
112
jsonp: 'callback', // Mapped to jsonpCallback: 'callback'
113
jsonpCallback: 'handleResponse', // Mapped to jsonpCallbackName: 'handleResponse'
114
success: function(data) {
115
console.log('JSONP data:', data);
116
}
117
});
118
119
// Mixed jQuery and reqwest options
120
reqwest.compat({
121
url: '/api/upload',
122
type: 'POST', // jQuery style
123
processData: false, // reqwest style
124
contentType: false, // jQuery style
125
data: formData,
126
success: function(response) {
127
console.log('Upload complete:', response);
128
}
129
});
130
```
131
132
### Get Callback Prefix
133
134
Utility function that returns the current JSONP callback prefix used by reqwest.
135
136
```javascript { .api }
137
/**
138
* Returns the callback prefix used for JSONP requests
139
* @returns {string} Current callback prefix (format: 'reqwest_' + timestamp)
140
*/
141
reqwest.getcallbackPrefix();
142
```
143
144
**Usage Examples:**
145
146
```javascript
147
// Get current callback prefix
148
const prefix = reqwest.getcallbackPrefix();
149
console.log('JSONP callback prefix:', prefix);
150
// Output: "reqwest_1698765432123"
151
152
// Use in custom JSONP handling
153
const customCallback = prefix + '_custom_' + Math.random();
154
reqwest({
155
url: 'https://api.example.com/jsonp?callback=' + customCallback,
156
type: 'jsonp',
157
jsonpCallbackName: customCallback,
158
success: function(data) {
159
console.log('Custom JSONP callback executed:', data);
160
}
161
});
162
```
163
164
## Migration from jQuery
165
166
### Direct Replacement
167
168
```javascript
169
// jQuery AJAX
170
$.ajax({
171
url: '/api/users',
172
type: 'GET',
173
dataType: 'json',
174
success: function(data) {
175
console.log('Users loaded:', data);
176
},
177
error: function(xhr, status, error) {
178
console.log('Failed to load users');
179
}
180
});
181
182
// Reqwest equivalent using compat
183
reqwest.compat({
184
url: '/api/users',
185
type: 'GET',
186
dataType: 'json',
187
success: function(data) {
188
console.log('Users loaded:', data);
189
},
190
error: function(xhr, type, error) {
191
console.log('Failed to load users');
192
}
193
});
194
```
195
196
### Global Setup Migration
197
198
```javascript
199
// jQuery global setup
200
$.ajaxSetup({
201
timeout: 10000,
202
beforeSend: function(xhr) {
203
xhr.setRequestHeader('X-API-Key', 'your-api-key');
204
},
205
error: function(xhr, status, error) {
206
console.log('Global error handler:', error);
207
}
208
});
209
210
// Reqwest equivalent
211
reqwest.ajaxSetup({
212
timeout: 10000,
213
before: function(xhr) {
214
xhr.setRequestHeader('X-API-Key', 'your-api-key');
215
},
216
error: function(xhr, type, error) {
217
console.log('Global error handler:', error);
218
}
219
});
220
```
221
222
### Promise Style Migration
223
224
```javascript
225
// jQuery with promises
226
$.ajax({
227
url: '/api/data',
228
type: 'POST',
229
data: { key: 'value' }
230
})
231
.done(function(data) {
232
console.log('Success:', data);
233
})
234
.fail(function(xhr, status, error) {
235
console.log('Error:', error);
236
})
237
.always(function() {
238
console.log('Complete');
239
});
240
241
// Reqwest equivalent (no compat needed for promises)
242
reqwest({
243
url: '/api/data',
244
method: 'POST',
245
data: { key: 'value' }
246
})
247
.then(function(data) {
248
console.log('Success:', data);
249
})
250
.fail(function(xhr, type, error) {
251
console.log('Error:', error);
252
})
253
.always(function() {
254
console.log('Complete');
255
});
256
```
257
258
## Ender Framework Integration
259
260
When reqwest is used with Ender, additional jQuery-style methods become available:
261
262
### Ender Ajax Methods
263
264
```javascript { .api }
265
// Available when reqwest is used with Ender
266
$.ajax(options); // Alias for reqwest
267
$.ajax.compat(options); // Alias for reqwest.compat
268
$.ajaxSetup(options); // Alias for reqwest.ajaxSetup
269
```
270
271
### Ender Setup for jQuery Compatibility
272
273
```javascript
274
// Make compat mode the default in Ender
275
$.ajax.compat && $.ender({ ajax: $.ajax.compat });
276
277
// Now all $.ajax calls use jQuery-compatible options
278
$.ajax({
279
url: '/api/data',
280
type: 'POST', // Will be mapped to method
281
dataType: 'json', // Will be mapped to type
282
success: function(data) {
283
console.log('Data:', data);
284
}
285
});
286
```
287
288
## Advanced Configuration Patterns
289
290
### Environment-Specific Setup
291
292
```javascript
293
// Development environment
294
if (NODE_ENV === 'development') {
295
reqwest.ajaxSetup({
296
timeout: 60000, // Longer timeout for debugging
297
dataFilter: function(data, type) {
298
console.log('API Response:', type, data);
299
return data;
300
},
301
error: function(xhr, type, error) {
302
console.error('DEV ERROR:', {xhr, type, error});
303
}
304
});
305
}
306
307
// Production environment
308
if (NODE_ENV === 'production') {
309
reqwest.ajaxSetup({
310
timeout: 15000,
311
error: function(xhr, type, error) {
312
// Send errors to monitoring service
313
analytics.track('api_error', {
314
url: xhr.responseURL,
315
status: xhr.status,
316
error: error
317
});
318
}
319
});
320
}
321
```
322
323
### Authentication Integration
324
325
```javascript
326
// Set up automatic authentication
327
function setupAuthenticatedRequests() {
328
reqwest.ajaxSetup({
329
before: function(xhr) {
330
const token = localStorage.getItem('authToken');
331
if (token) {
332
xhr.setRequestHeader('Authorization', 'Bearer ' + token);
333
}
334
},
335
error: function(xhr, type, error) {
336
// Handle authentication errors globally
337
if (xhr.status === 401) {
338
localStorage.removeItem('authToken');
339
window.location.href = '/login';
340
}
341
}
342
});
343
}
344
345
// Initialize authentication setup
346
setupAuthenticatedRequests();
347
348
// All subsequent requests will include auth headers
349
reqwest({ url: '/api/protected-data' })
350
.then(function(data) {
351
console.log('Protected data:', data);
352
});
353
```
354
355
### API Response Normalization
356
357
```javascript
358
// Normalize different API response formats
359
reqwest.ajaxSetup({
360
dataFilter: function(data, type) {
361
if (type === 'json' && data) {
362
// Handle wrapped responses
363
if (data.status && data.data) {
364
return data.data;
365
}
366
367
// Handle paginated responses
368
if (data.results && Array.isArray(data.results)) {
369
data.items = data.results; // Normalize property name
370
return data;
371
}
372
373
// Handle error responses
374
if (data.error) {
375
throw new Error(data.error.message || 'API Error');
376
}
377
}
378
379
return data;
380
}
381
});
382
383
// All JSON responses are now normalized
384
reqwest({ url: '/api/users', type: 'json' })
385
.then(function(users) {
386
// users is already unwrapped from {status: 'ok', data: users}
387
console.log('Normalized users:', users);
388
});
389
```