-
Notifications
You must be signed in to change notification settings - Fork 2
/
jsonp.js
52 lines (39 loc) · 1.21 KB
/
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
var JSONp = {
callbacks : {},
callbackCount : 0,
buildQueryString : function( params ){
var qsArray = new Array();
// Build query string from JSON
for (var key in params.opts) {
if (params.opts.hasOwnProperty(key)) {
qsArray.push(key + "=" + encodeURIComponent(params.opts[key]));
}
}
// Append callback name
var cbFunc = 'JSONp.callbacks.' + params.cbID;
var cbName = params.callbackName || 'callback';
qsArray.push(cbName + "=" + cbFunc);
return qsArray.join('&');
},
get : function( params ){
// Generate call ID
var d = new Date();
this.callbackCount++;
params.cbID = 'cb' + d.getTime() + '_' + this.callbackCount;
// Assign callback function
this.callbacks[params.cbID] = function(json){
params.success(json);
// Cleanup script tags
var head = document.getElementsByTagName('head')[0];
var el = document.getElementById(params.cbID);
head.removeChild(el);
};
// Create script tag
var el = document.createElement('script');
el.src = params.url + '?' + this.buildQueryString(params);
el.id = params.cbID;
// Write into head tags
var head = document.getElementsByTagName('head')[0];
head.insertBefore(el, head.firstChild);
}
}