diff options
Diffstat (limited to 'modules/luci-base/htdocs/luci-static/resources/xhr.js')
-rw-r--r-- | modules/luci-base/htdocs/luci-static/resources/xhr.js | 48 |
1 files changed, 36 insertions, 12 deletions
diff --git a/modules/luci-base/htdocs/luci-static/resources/xhr.js b/modules/luci-base/htdocs/luci-static/resources/xhr.js index 701c12ac19..62b525ebb0 100644 --- a/modules/luci-base/htdocs/luci-static/resources/xhr.js +++ b/modules/luci-base/htdocs/luci-static/resources/xhr.js @@ -39,10 +39,11 @@ XHR = function() this._xmlHttp.abort(); } - this.get = function(url,data,callback) + this.get = function(url,data,callback,timeout) { this.reinit(); + var ts = Date.now(); var xhr = this._xmlHttp; var code = this._encode(data); @@ -56,43 +57,49 @@ XHR = function() xhr.open('GET', url, true); + if (!isNaN(timeout)) + xhr.timeout = timeout; + xhr.onreadystatechange = function() { if (xhr.readyState == 4) { var json = null; if (xhr.getResponseHeader("Content-Type") == "application/json") { try { - json = eval('(' + xhr.responseText + ')'); + json = JSON.parse(xhr.responseText); } catch(e) { json = null; } } - callback(xhr, json); + callback(xhr, json, Date.now() - ts); } } xhr.send(null); } - this.post = function(url,data,callback) + this.post = function(url,data,callback,timeout) { this.reinit(); + var ts = Date.now(); var xhr = this._xmlHttp; var code = this._encode(data); xhr.onreadystatechange = function() { if (xhr.readyState == 4) - callback(xhr); + callback(xhr, null, Date.now() - ts); } xhr.open('POST', url, true); + + if (!isNaN(timeout)) + xhr.timeout = timeout; + xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); - xhr.setRequestHeader('Content-length', code.length); - xhr.setRequestHeader('Connection', 'close'); xhr.send(code); } @@ -170,7 +177,7 @@ XHR.get = function(url, data, callback) (new XHR()).get(url, data, callback); } -XHR.poll = function(interval, url, data, callback) +XHR.poll = function(interval, url, data, callback, post) { if (isNaN(interval) || interval < 1) interval = 5; @@ -183,22 +190,37 @@ XHR.poll = function(interval, url, data, callback) for (var i = 0, e = XHR._q[0]; i < XHR._q.length; e = XHR._q[++i]) { if (!(XHR._t % e.interval) && !e.xhr.busy()) - e.xhr.get(e.url, e.data, e.callback); + e.xhr[post ? 'post' : 'get'](e.url, e.data, e.callback, e.interval * 1000 * 5 - 5); } XHR._t++; }; } - XHR._q.push({ + var e = { interval: interval, callback: callback, url: url, data: data, xhr: new XHR() - }); + }; - XHR.run(); + XHR._q.push(e); + + return e; +} + +XHR.stop = function(e) +{ + for (var i = 0; XHR._q && XHR._q[i]; i++) { + if (XHR._q[i] === e) { + e.xhr.cancel(); + XHR._q.splice(i, 1); + return true; + } + } + + return false; } XHR.halt = function() @@ -239,3 +261,5 @@ XHR.running = function() { return !!(XHR._r && XHR._i); } + +document.addEventListener('DOMContentLoaded', XHR.run); |