source: trunk/phpgwapi/js/tools/xconnector.js @ 2420

Revision 2420, 8.2 KB checked in by rodsouza, 14 years ago (diff)

Ticket #1009 - Adicinando scripts para possibilitar o não reload de pagina. Habilitado para o Admin.

Line 
1(function()
2{
3        var _THREADS = [];
4        var _ie;
5
6        function _config(pObj, pEvent, pHandler)
7        {
8                if ( typeof pObj == 'object' )
9                {
10                        if ( pEvent.substring(0, 2) == 'on' )
11                                pEvent = pEvent.substring(2, pEvent.length);
12
13                        if ( pObj.addEventListener )
14                                pObj.addEventListener(pEvent, pHandler, false);
15                        else if ( pObj.attachEvent )
16                                pObj.attachEvent('on' + pEvent, pHandler);
17                }
18        }
19
20        // xhr = XMLHttpRequest
21        function _xhr()
22        {
23                try
24                {
25                        return new XMLHttpRequest();
26                }
27                catch ( _e )
28                {
29                        _ie = true;
30                        try
31                        {
32                                return new ActiveXObject('Msxml2.XMLHTTP');
33                        }
34                        catch ( _e1 )
35                        {
36                                try
37                                {
38                                        return new ActiveXObject('Microsoft.XMLHTTP');
39                                }
40                                catch ( _e2 )
41                                {
42                                        return false;
43                                }
44                        }
45                }
46        }
47
48        function _HANDLER()
49        {
50                var _ID = arguments[0];
51
52                if  ( _THREADS[_ID] )
53                {
54                        if ( _ie && _THREADS[_ID]._XHR.readyState != 4 )
55                                return false;
56
57                        switch ( _THREADS[_ID]._XHR.readyState )
58                        {
59                                case 3 :
60                                        if ( _THREADS[_ID]._HANDLER.stream )
61                                        {
62                                                var _data = _THREADS[_ID]._XHR.responseText.substr(_THREADS[_ID]._index).replace(/^ +| +$/g, '');
63                                                //alert(_data);
64                                                _THREADS[_ID]._rtlen = _THREADS[_ID]._XHR.responseText.length;
65
66                                                if ( _THREADS[_ID]._index < _THREADS[_ID]._rtlen && _data.length )
67                                                        try
68                                                        {
69                                                                _THREADS[_ID]._HANDLER.stream(_data);
70                                                        }
71                                                        catch(_e)
72                                                        {
73                                                                //alert("#stream\n\n" + _e + "\n\n" + _e.description);
74                                                        }
75
76                                                if ( _THREADS[ _ID ] )
77                                                        _THREADS[ _ID ]._index = _THREADS[ _ID ]._rtlen;
78                                        }
79                                break;
80                                case 4 :
81                                        try
82                                        {
83                                                switch ( _THREADS[ _ID ]._XHR.status )
84                                                {
85                                                        case 200:
86                                                                var _data = ( _THREADS[ _ID ]._MODE == 'XML' ) ?
87                                                                        _THREADS[ _ID ]._XHR.responseXML :
88                                                                        _THREADS[ _ID ]._XHR.responseText;
89
90                                                                if ( _ie && _THREADS[ _ID ]._HANDLER.stream )
91                                                                        _THREADS[ _ID ]._HANDLER.stream(_data);
92
93                                                                var _request = ( _THREADS[ _ID ]._HANDLER.request ) ?
94                                                                        _THREADS[ _ID ]._HANDLER.request : false;
95
96                                                                if ( _THREADS[ _ID ]._MODE == 'XML' && _data.documentElement && _data.documentElement.hasAttribute( 'ControllerKey' ) )
97                                                                {
98                                                                        this._CONTROLLER_KEY = _data.documentElement.getAttribute( 'ControllerKey' );
99                                                                        _data.documentElement.removeAttribute( 'ControllerKey' );
100                                                                }
101
102                                                                delete _THREADS[ _ID ];
103
104                                                                if ( _request )
105                                                                        try
106                                                                        {
107                                                                                _request( _data );
108                                                                        }
109                                                                        catch( e )
110                                                                        {
111                                                                                //alert("#request\n\n" + _e + "\n\n" + _e.description);
112                                                                        }
113
114                                                        break; // [case : status 200]
115                                                        case 404:
116                                                                delete _THREADS[ _ID ];
117                                                                alert( 'Page Not Found!' );
118                                                        break; // [case : status 404]
119                                                        default:
120                                                                delete _THREADS[ _ID ];
121                                                }
122                                        }
123                                        catch( e )
124                                        {
125                                        }
126                                break;
127                                default :
128                        }
129                }
130        }
131
132        function _execute( )
133        {
134                var _ID = arguments[0];
135
136                var _ACTION = 'act=' + _ID;
137                //var _TARGET = this._PATH + _THREADS[ _ID ]._ACCESS;
138                var _TARGET = _THREADS[ _ID ]._ACCESS;
139
140                var _SEND = null;
141
142                //_TARGET += ( this._CONTROLLER ) ?
143                //      this._CONTROLLER  : 'controller.php';
144
145                //if ( _THREADS[_ID]._METHOD == 'GET' )
146                //      _TARGET += '?' + _ACTION;
147
148                //_TARGET += _ID;
149
150                _THREADS[ _ID ]._XHR.open( ( ( _THREADS[ _ID ]._POST ) ? 'POST' : 'GET' ), _TARGET, true);
151
152                if ( _THREADS[ _ID ]._POST )
153                {
154                        _THREADS[ _ID ]._XHR.setRequestHeader( 'Content-Type','application/x-www-form-urlencoded' );
155                        _THREADS[ _ID ]._XHR.setRequestHeader( 'Cache-Control',  'no-store, no-cache, must-revalidate' );
156                        _THREADS[ _ID ]._XHR.setRequestHeader( 'Cache-Control', 'post-check=0, pre-check=0' );
157                        _THREADS[ _ID ]._XHR.setRequestHeader( 'Pragma', 'no-cache' );
158
159                        _SEND = _THREADS[ _ID ]._POST;
160
161                        if ( this._CONTROLLER_KEY && typeof _SEND.documentElement == 'object' )
162                                _SEND.documentElement.setAttribute( 'ControllerKey', this._CONTROLLER_KEY );
163
164                }
165
166                _THREADS[ _ID ]._XHR.setRequestHeader( 'BackgroundRequest', Date.parse( new Date ) );
167
168                var _this = this;
169                _THREADS[ _ID ]._XHR.onreadystatechange = function( ){ _HANDLER.call( _this, _ID ); };
170                _THREADS[ _ID ]._XHR.send( _SEND );
171        }
172
173        function usage( )
174        {
175                return ""+
176                        "Description:\n"+
177                        "\t<obj>.go({string access, [mixed handler[, XMLObject post]]})\n\n"+
178                        "Parameters:\n"+
179                        "\taccess : assinatura de acesso à camada de controle.\n"+
180                        "\thandler : uma função a ser executada no fim da requisição\n"+
181                        "\t\tou um objeto que poderá conter dois índices sendo\n"+
182                        "\t\tque ambos deverão ser uma função que será executada\n"+
183                        "\t\tconforme o status do objeto xhr, sendo que na posição\n"+
184                        "\t\t'stream' será a função a ser executada a cada iteração\n"+
185                        "\t\tdo objeto xhr e na posição 'request' será a função\n"+
186                        "\t\ta ser executada no fim da requisição.\n"+
187                        "\tpost : se especificado deverá ser uma query string ou um\n"+
188                        "\tXML bem formatado.\n\n";
189        }
190
191        // @PARAM <string> access :
192        //              assinatura de acesso à camada de controle
193        //
194        // @PARAM <object> handler :
195        //              OBS : neste caso a conexão assumirá que se trata de uma stream
196        //              objeto contendo dois duas funções, sendo,
197        //              no índice stream deverá conter uma função que será execultada
198        //              a cada mudança de status do objeto xhr
199        //
200        // @PARAM <function> handler :
201        //              funcão a ser executada no retorno da requisição
202        //              OBS : neste caso a conexão assumirá que se trata de uma
203        //              requisição função que será execultada no final da requisição
204        //
205        // @PARAM <XMLObject> post:
206        //              este parâmetro define se a conexão é via GET ou POST
207        //              caso o parâmetro não esteja presente a conexão será execultada
208        //              via GET, por outro lado, caso ele exista deverá ser uma query
209        //              string válida ou um xml bem formatado
210        //
211        function go( )
212        {
213                if ( arguments.length != 1 )
214                        return { 'error' : "#0\n\n" + usage( ) };
215
216                var _argv = arguments[ 0 ];
217
218                if ( ( ! _argv.access ) || ( typeof _argv.access != 'string' ) || ( ! _argv.access.length ) )
219                        return { 'error' : "#1\n\n" + usage( ) };
220
221                var _ID = _argv.access;
222
223                _THREADS[ _ID ] = {
224                        '_ACCESS'       : _argv.access,
225                        '_HANDLER'      : { },
226                        '_POST'         : ( ( _argv.post ) ? _argv.post : false ),  // [GET | POST]
227                        '_MODE'         : 'TEXT', // [XML | TEXT]
228                        '_TYPE'         : null, // [4 for request | 3 for stream]
229                        '_XHR'          : null  // [4 for request | 3 for stream]
230                };
231
232                if ( _argv.mode && ( _argv.mode == 'XML' || _argv.mode == 'TEXT' ) )
233                        _THREADS[ _ID ] = _argv.mode;
234
235                if ( _argv.handler )
236                        switch ( typeof _argv.handler )
237                        {
238                                case 'function' :
239                                        _THREADS[ _ID ]._HANDLER = { 'request' : _argv.handler };
240                                        break;
241                                case 'object' :
242                                        for ( var i in _argv.handler )
243                                                if ( i != 'stream' && i != 'request' )
244                                                {
245                                                        delete _THREADS[ _ID ];
246                                                        return { 'error' : "#2\n\n" + usage( ) };
247                                                }
248                                                else if ( i == 'stream' )
249                                                {
250                                                        _THREADS[ _ID ]._index = 0;
251                                                        _THREADS[ _ID ]._rtlen = 0;
252                                                }
253                                                _THREADS[ _ID ]._HANDLER = _argv.handler;
254                                        break;
255                        }
256
257                if ( ! ( _THREADS[ _ID ]._XHR = _xhr( ) ) )
258                {
259                        delete _THREADS[_ID];
260                        return { 'error' : "#3 it cannot make a xhr object" };
261                }
262
263                _execute.call(this, _ID);
264
265                return { 'success' : "your thread is running and the response will be manipulated by the handler" };
266        }
267
268        function _abort()
269        {
270                for ( var _ID in _THREADS )
271                {
272                        // @TODO
273                        // try/catch for unknown error of IE.
274                        // Check, store and retrieve the try/catch.
275                        try
276                        {
277                                if ( _THREADS[_ID] && _THREADS[_ID]._XHR && _THREADS[_ID]._XHR.abort )
278                                        _THREADS[_ID]._XHR.abort();
279
280                                delete _THREADS[_ID];
281                        }
282                        catch(e){}
283                }
284        }
285
286        function Connector( )
287        {
288                var _argv = arguments;
289
290                if ( ( _argv.length == 1 ) && ( typeof _argv[0] == 'object' ) )
291                {
292                        _argv = _argv[ 0 ];
293
294                        this._PATH = '';
295
296                        if ( _argv.path && ( typeof _argv.path == 'string' ) && this._PATH.length )
297                        {
298                                if ( _argv.path.indexOf('/') != 0 )
299                                        _argv.path = '/' + _argv.path;
300
301                                if ( _argv.path.lastIndexOf('/') != ( _argv.path.length - 1) )
302                                        _argv.path += '/';
303
304                                this._PATH = _argv.path;
305                        }
306
307                        this._CONTROLLER = ( _argv.controller ) ?
308                                _argv.controller : false;
309
310                        this._CONTROLLER_KEY = ( _argv.key ) ?
311                                _argv.key : false;
312                }
313        }
314
315        Connector.prototype.go = go;
316        Connector.prototype.abort = _abort;
317        window.XConnector = Connector;
318
319        _config( window, 'onbeforeunload', _abort );
320}
321)();
Note: See TracBrowser for help on using the repository browser.