Upgrade to ExtJS 3.3.1 - Released 11/30/2010
[extjs.git] / src / ext-core / examples / jsonp / jsonp.js
1 /*!
2  * Ext JS Library 3.3.1
3  * Copyright(c) 2006-2010 Sencha Inc.
4  * licensing@sencha.com
5  * http://www.sencha.com/license
6  */
7 Ext.ns('Ext.ux');
8
9 Ext.ux.JSONP = (function(){
10     var _queue = [],
11         _current = null,
12         _nextRequest = function() {
13             _current = null;
14             if(_queue.length) {
15                 _current = _queue.shift();
16                         _current.script.src = _current.url + '?' + _current.params;
17                         document.getElementsByTagName('head')[0].appendChild(_current.script);
18             }
19         };
20
21     return {
22         request: function(url, o) {
23             if(!url) {
24                 return;
25             }
26             var me = this;
27
28             o.params = o.params || {};
29             if(o.callbackKey) {
30                 o.params[o.callbackKey] = 'Ext.ux.JSONP.callback';
31             }
32             var params = Ext.urlEncode(o.params);
33
34             var script = document.createElement('script');
35                         script.type = 'text/javascript';
36
37             if(o.isRawJSON) {
38                 if(Ext.isIE) {
39                     Ext.fly(script).on('readystatechange', function() {
40                         if(script.readyState == 'complete') {
41                             var data = script.innerHTML;
42                             if(data.length) {
43                                 me.callback(Ext.decode(data));
44                             }
45                         }
46                     });
47                 }
48                 else {
49                      Ext.fly(script).on('load', function() {
50                         var data = script.innerHTML;
51                         if(data.length) {
52                             me.callback(Ext.decode(data));
53                         }
54                     });
55                 }
56             }
57
58             _queue.push({
59                 url: url,
60                 script: script,
61                 callback: o.callback || function(){},
62                 scope: o.scope || window,
63                 params: params || null
64             });
65
66             if(!_current) {
67                 _nextRequest();
68             }
69         },
70
71         callback: function(json) {
72             _current.callback.apply(_current.scope, [json]);
73             Ext.fly(_current.script).removeAllListeners();
74             document.getElementsByTagName('head')[0].removeChild(_current.script);
75             _nextRequest();
76         }
77     }
78 })();