-
Notifications
You must be signed in to change notification settings - Fork 12
/
jquery.jsonp.js
288 lines (229 loc) · 8.08 KB
/
jquery.jsonp.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
/*
* jQuery JSONP Core Plugin 2.3.1 (2012-05-16)
*
* https://github.com/jaubourg/jquery-jsonp
*
* Copyright (c) 2012 Julian Aubourg
*
* This document is licensed as free software under the terms of the
* MIT License: http://www.opensource.org/licenses/mit-license.php
*/
( function( $ ) {
// ###################### UTILITIES ##
// Noop
function noop() {
}
// Generic callback
function genericCallback( data ) {
lastValue = [ data ];
}
// Call if defined
function callIfDefined( method , object , parameters , returnFlag ) {
try {
returnFlag = method && method.apply( object.context || object , parameters );
} catch( _ ) {
returnFlag = !1;
}
return returnFlag;
}
// Give joining character given url
function qMarkOrAmp( url ) {
return /\?/ .test( url ) ? "&" : "?";
}
var // String constants (for better minification)
STR_ASYNC = "async",
STR_CHARSET = "charset",
STR_EMPTY = "",
STR_ERROR = "error",
STR_INSERT_BEFORE = "insertBefore",
STR_JQUERY_JSONP = "_jqjsp",
STR_ON = "on",
STR_ON_CLICK = STR_ON + "click",
STR_ON_ERROR = STR_ON + STR_ERROR,
STR_ON_LOAD = STR_ON + "load",
STR_ON_READY_STATE_CHANGE = STR_ON + "readystatechange",
STR_READY_STATE = "readyState",
STR_REMOVE_CHILD = "removeChild",
STR_SCRIPT_TAG = "<script>",
STR_SUCCESS = "success",
STR_TIMEOUT = "timeout",
// Window
win = window,
// Deferred
Deferred = $.Deferred,
// Head element
head = $( "head" )[ 0 ] || document.documentElement,
// Page cache
pageCache = {},
// Counter
count = 0,
// Last returned value
lastValue,
// ###################### DEFAULT OPTIONS ##
xOptionsDefaults = {
//beforeSend: undefined,
//cache: false,
callback: STR_JQUERY_JSONP,
//callbackParameter: undefined,
//charset: undefined,
//complete: undefined,
//context: undefined,
//data: "",
//dataFilter: undefined,
//error: undefined,
//pageCache: false,
//success: undefined,
//timeout: 0,
//traditional: false,
url: location.href
},
// opera demands sniffing :/
opera = win.opera;
// ###################### MAIN FUNCTION ##
function jsonp( xOptions ) {
// Build data with default
xOptions = $.extend( {} , xOptionsDefaults , xOptions );
// References to xOptions members (for better minification)
var successCallback = xOptions.success,
errorCallback = xOptions.error,
completeCallback = xOptions.complete,
dataFilter = xOptions.dataFilter,
callbackParameter = xOptions.callbackParameter,
successCallbackName = xOptions.callback,
cacheFlag = xOptions.cache,
pageCacheFlag = xOptions.pageCache,
charset = xOptions.charset,
url = xOptions.url,
data = xOptions.data,
timeout = xOptions.timeout,
pageCached,
// Abort/done flag
done = 0,
// Life-cycle functions
cleanUp = noop,
// Support vars
supportOnload,
supportOnreadystatechange,
// Request execution vars
firstChild,
script,
scriptAfter,
timeoutTimer;
// If we have Deferreds:
// - substitute callbacks
// - promote xOptions to a promise
Deferred && Deferred(function( defer ) {
defer.done( successCallback ).fail( errorCallback );
successCallback = defer.resolve;
errorCallback = defer.reject;
}).promise( xOptions );
// Create the abort method
xOptions.abort = function() {
!( done++ ) && cleanUp();
};
// Call beforeSend if provided (early abort if false returned)
if ( callIfDefined( xOptions.beforeSend, xOptions , [ xOptions ] ) === !1 || done ) {
return xOptions;
}
// Control entries
url = url || STR_EMPTY;
data = data ? ( (typeof data) == "string" ? data : $.param( data , xOptions.traditional ) ) : STR_EMPTY;
// Build final url
url += data ? ( qMarkOrAmp( url ) + data ) : STR_EMPTY;
// Add callback parameter if provided as option
callbackParameter && ( url += qMarkOrAmp( url ) + encodeURIComponent( callbackParameter ) + "=?" );
// Add anticache parameter if needed
!cacheFlag && !pageCacheFlag && ( url += qMarkOrAmp( url ) + "_" + ( new Date() ).getTime() + "=" );
// Replace last ? by callback parameter
url = url.replace( /=\?(&|$)/ , "=" + successCallbackName + "$1" );
// Success notifier
function notifySuccess( json ) {
if ( !( done++ ) ) {
cleanUp();
// Pagecache if needed
pageCacheFlag && ( pageCache [ url ] = { s: [ json ] } );
// Apply the data filter if provided
dataFilter && ( json = dataFilter.apply( xOptions , [ json ] ) );
// Call success then complete
callIfDefined( successCallback , xOptions , [ json , STR_SUCCESS ] );
callIfDefined( completeCallback , xOptions , [ xOptions , STR_SUCCESS ] );
}
}
// Error notifier
function notifyError( type ) {
if ( !( done++ ) ) {
// Clean up
cleanUp();
// If pure error (not timeout), cache if needed
pageCacheFlag && type != STR_TIMEOUT && ( pageCache[ url ] = type );
// Call error then complete
callIfDefined( errorCallback , xOptions , [ xOptions , type ] );
callIfDefined( completeCallback , xOptions , [ xOptions , type ] );
}
}
// Check page cache
if ( pageCacheFlag && ( pageCached = pageCache[ url ] ) ) {
pageCached.s ? notifySuccess( pageCached.s[ 0 ] ) : notifyError( pageCached );
} else {
// Install the generic callback
// (BEWARE: global namespace pollution ahoy)
win[ successCallbackName ] = genericCallback;
// Create the script tag
script = $( STR_SCRIPT_TAG )[ 0 ];
script.id = STR_JQUERY_JSONP + count++;
// Set charset if provided
if ( charset ) {
script[ STR_CHARSET ] = charset;
}
opera && opera.version() < 11.60 ?
// onerror is not supported: do not set as async and assume in-order execution.
// Add a trailing script to emulate the event
( ( scriptAfter = $( STR_SCRIPT_TAG )[ 0 ] ).text = "document.getElementById('" + script.id + "')." + STR_ON_ERROR + "()" )
:
// onerror is supported: set the script as async to avoid requests blocking each others
( script[ STR_ASYNC ] = STR_ASYNC )
;
// Internet Explorer: event/htmlFor trick
if ( STR_ON_READY_STATE_CHANGE in script ) {
script.htmlFor = script.id;
script.event = STR_ON_CLICK;
}
// Attached event handlers
script[ STR_ON_LOAD ] = script[ STR_ON_ERROR ] = script[ STR_ON_READY_STATE_CHANGE ] = function ( result ) {
// Test readyState if it exists
if ( !script[ STR_READY_STATE ] || !/i/.test( script[ STR_READY_STATE ] ) ) {
try {
script[ STR_ON_CLICK ] && script[ STR_ON_CLICK ]();
} catch( _ ) {}
result = lastValue;
lastValue = 0;
result ? notifySuccess( result[ 0 ] ) : notifyError( STR_ERROR );
}
};
// Set source
script.src = url;
// Re-declare cleanUp function
cleanUp = function( i ) {
timeoutTimer && clearTimeout( timeoutTimer );
script[ STR_ON_READY_STATE_CHANGE ] = script[ STR_ON_LOAD ] = script[ STR_ON_ERROR ] = null;
head[ STR_REMOVE_CHILD ]( script );
scriptAfter && head[ STR_REMOVE_CHILD ]( scriptAfter );
};
// Append main script
head[ STR_INSERT_BEFORE ]( script , ( firstChild = head.firstChild ) );
// Append trailing script if needed
scriptAfter && head[ STR_INSERT_BEFORE ]( scriptAfter , firstChild );
// If a timeout is needed, install it
timeoutTimer = timeout > 0 && setTimeout( function() {
notifyError( STR_TIMEOUT );
} , timeout );
}
return xOptions;
}
// ###################### SETUP FUNCTION ##
jsonp.setup = function( xOptions ) {
$.extend( xOptionsDefaults , xOptions );
};
// ###################### INSTALL in jQuery ##
$.jsonp = jsonp;
} )( jQuery );