ajax.js 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. function AjaxErrorBadStatusCode(message) { this.name = 'AjaxErrorBadStatusCode'; this.message = message; };
  2. AjaxErrorBadStatusCode.prototype = new Error();
  3. var ajax = {loaded: false};
  4. ajax.create = function() {
  5. if(typeof XMLHttpRequest !== 'undefined') {
  6. return new XMLHttpRequest();
  7. };
  8. var versions = [
  9. "MSXML2.XmlHttp.6.0",
  10. "MSXML2.XmlHttp.5.0",
  11. "MSXML2.XmlHttp.4.0",
  12. "MSXML2.XmlHttp.3.0",
  13. "MSXML2.XmlHttp.2.0",
  14. "Microsoft.XmlHttp"
  15. ];
  16. var xhr;
  17. for(var i = 0; i < versions.length; i++) {
  18. try {
  19. xhr = new ActiveXObject(versions[i]);
  20. break;
  21. } catch(e) {
  22. // Silent
  23. };
  24. };
  25. return xhr;
  26. };
  27. ajax.send = function(url, callback, method, data, async) {
  28. if(async === undefined) {
  29. async = true;
  30. };
  31. var a = ajax.create();
  32. a.open(method, url, async);
  33. a.onreadystatechange = function() {
  34. // a.readyState:
  35. // 0 - UNSENT
  36. // 1 - OPENED
  37. // 2 - HEADERS_RECEIVED
  38. // 3 - LOADING
  39. // 4 - DONE
  40. callback(method, data, a.readyState, a.status, a.responseText);
  41. };
  42. if(method == 'POST') {
  43. a.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
  44. };
  45. a.send(data);
  46. };
  47. ajax.delete = function(url, data, callback, async) {
  48. var query = [];
  49. for(var key in data) {
  50. query.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]));
  51. };
  52. ajax.send(url + (query.length ? '?' + query.join('&') : ''), callback, 'DELETE', null, async);
  53. };
  54. ajax.get = function(url, data, callback, async) {
  55. var query = [];
  56. for(var key in data) {
  57. query.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]));
  58. };
  59. ajax.send(url + (query.length ? '?' + query.join('&') : ''), callback, 'GET', null, async);
  60. };
  61. ajax.getJSON = function(url, data, callbackSuccess, callbackError, async) {
  62. ajax.get(url, data, function(method, data, readyState, status, responseText) {
  63. if(readyState == 4) {
  64. if(status == 200) {
  65. try {
  66. var r = JSON.parse(responseText);
  67. if(callbackSuccess) {
  68. callbackSuccess(method, data, readyState, status, r);
  69. };
  70. } catch(e) {
  71. if(callbackError) {
  72. callbackError(method, data, readyState, status, e);
  73. };
  74. };
  75. } else {
  76. if(callbackError) {
  77. var e = new AjaxErrorBadStatusCode('Bad status code '+status);
  78. callbackError(method, data, readyState, status, e);
  79. };
  80. };
  81. };
  82. }, async);
  83. };
  84. ajax.post = function(url, data, callback, async) {
  85. var query = [];
  86. for (var key in data) {
  87. query.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]));
  88. };
  89. ajax.send(url, callback, 'POST', query.join('&'), async);
  90. };
  91. ajax.postJSON = function(url, data, callbackSuccess, callbackError, async) {
  92. ajax.post(url, data, function(method, data, readyState, status, responseText) {
  93. if(readyState == 4) {
  94. if(status == 200) {
  95. try {
  96. var r = JSON.parse(responseText);
  97. if(callbackSuccess) {
  98. callbackSuccess(method, data, readyState, status, r);
  99. };
  100. } catch(e) {
  101. if(callbackError) {
  102. callbackError(method, data, readyState, status, e);
  103. };
  104. };
  105. } else {
  106. if(callbackError) {
  107. var e = new AjaxErrorBadStatusCode('Bad status code '+status);
  108. callbackError(method, data, readyState, status, e);
  109. };
  110. };
  111. };
  112. }, async);
  113. };
  114. ajax.loadTag = function(tag, url, func, field) {
  115. if((typeof window[func] === 'function') || field != null) {
  116. if(!!!tag.className.match(new RegExp('(\\s|^)loading(\\s|$)'))) {
  117. tag.className += " loading";
  118. ajax.getJSON(url, {}, function(method, data, readyState, status, responseData) {
  119. try {
  120. if(typeof window[func] === 'function') {
  121. var html = window[func](tag, responseData);
  122. tag.innerHTML = html;
  123. } else if(field != null) {
  124. tag.innerHTML = responseData[field];
  125. };
  126. } catch(e) {
  127. console.log('ajax.loadTag', 'e', e);
  128. };
  129. tag.className = tag.className.replace(new RegExp('(\\s|^)loading(\\s|$)'), ' ').trim();
  130. }, function(method, data, readyState, status, responseData) {
  131. tag.className = tag.className.replace(new RegExp('(\\s|^)loading(\\s|$)'), ' ').trim();
  132. });
  133. };
  134. };
  135. };
  136. ajax.processTag = function(tag) {
  137. var get = tag.getAttribute('data-ajax-get');
  138. var func = tag.getAttribute('data-ajax-func');
  139. var field = tag.getAttribute('data-ajax-field');
  140. var delay = tag.getAttribute('data-ajax-delay');
  141. if((get && get != null) && ((func && func != null) || (field && field != null))) {
  142. if(delay == null) {
  143. ajax.loadTag(tag, get, func, field);
  144. } else {
  145. setTimeout(function() {
  146. ajax.loadTag(tag, get, func, field);
  147. }, delay);
  148. };
  149. };
  150. };
  151. ajax.processTags = function() {
  152. var tags = document.querySelectorAll('[data-ajax-get]');
  153. for(var key in tags) if(tags.hasOwnProperty(key)) {
  154. var tag = tags[key];
  155. ajax.processTag(tag);
  156. };
  157. };
  158. ajax.reloadTag = function(tag) {
  159. ajax.processTag(tag);
  160. };
  161. ajax.reloadTagById = function(id) {
  162. var tag = document.getElementById(id)
  163. if(tag != null) {
  164. ajax.reloadTag(tag);
  165. };
  166. };
  167. ajax.processFormSubmit = function(event) {
  168. if(!event) var event = window.event;
  169. event.preventDefault();
  170. var form = event.target;
  171. var func = form.getAttribute('data-ajax-func');
  172. if(func && func != null && typeof window[func] === 'function') {
  173. if(!!!form.className.match(new RegExp('(\\s|^)loading(\\s|$)'))) {
  174. form.className += " loading";
  175. var data = {};
  176. var inputs = form.querySelectorAll("input,select,textarea");
  177. for(var i=0,m=inputs.length-1; i<=m; i++) {
  178. data[inputs[i].name] = inputs[i].value;
  179. };
  180. var ajaxFunc = ajax.get;
  181. if(form.method == "post") { ajaxFunc = ajax.post; };
  182. ajaxFunc(form.action, data, function(method, data, readyState, status, responseText) {
  183. if(readyState == 4) {
  184. var error = (status == 200);
  185. var responseData = responseText;
  186. try {
  187. var responseData = JSON.parse(responseText);
  188. } catch(e) {
  189. console.log('ajax.processFormSubmit', 'e', e);
  190. };
  191. try {
  192. window[func](form, responseData, error, status);
  193. } catch(e) {
  194. console.log('ajax.processFormSubmit', 'e', e);
  195. };
  196. form.className = form.className.replace(new RegExp('(\\s|^)loading(\\s|$)'), ' ').trim();
  197. };
  198. });
  199. };
  200. };
  201. };
  202. ajax.processForm = function(form) {
  203. var is = form.getAttribute('data-ajax-form');
  204. var func = form.getAttribute('data-ajax-func');
  205. if((is && is != null && is == "true") && (func && func != null)) {
  206. if(window.attachEvent) {
  207. form.attachEvent('onsubmit', ajax.processFormSubmit);
  208. } else if(window.addEventListener) {
  209. form.addEventListener('submit', ajax.processFormSubmit, false);
  210. };
  211. };
  212. };
  213. ajax.processForms = function() {
  214. var forms = document.querySelectorAll('[data-ajax-form]');
  215. for(var key in forms) if(forms.hasOwnProperty(key)) {
  216. var form = forms[key];
  217. ajax.processForm(form);
  218. };
  219. };
  220. ajax.processCheckboxClick = function(event) {
  221. if(!event) var event = window.event;
  222. event.preventDefault();
  223. var checkbox = event.target;
  224. var on = checkbox.getAttribute('data-ajax-on');
  225. var off = checkbox.getAttribute('data-ajax-off');
  226. var func = checkbox.getAttribute('data-ajax-func');
  227. var box = checkbox.parentNode;
  228. if(!!box.className.match(new RegExp('(\\s|^)loading(\\s|$)'))) {
  229. event.preventDefault();
  230. event.stopPropagation();
  231. return false;
  232. };
  233. box.className += " loading";
  234. ajax.post(checkbox.checked ? on : off, {}, function(method, data, readyState, status, responseText) {
  235. if(readyState == 4) {
  236. var error = (status == 200);
  237. var responseData = responseText;
  238. try {
  239. var responseData = JSON.parse(responseText);
  240. } catch(e) {
  241. console.log('ajax.processCheckboxClick', 'e', e);
  242. };
  243. try {
  244. window[func](checkbox, responseData, error, status);
  245. } catch(e) {
  246. console.log('ajax.processCheckboxClick', 'e', e);
  247. };
  248. box.className = box.className.replace(new RegExp('(\\s|^)loading(\\s|$)'), ' ').trim();
  249. };
  250. });
  251. return true;
  252. };
  253. ajax.processCheckbox = function(checkbox) {
  254. var is = checkbox.getAttribute('data-ajax-checkbox');
  255. var on = checkbox.getAttribute('data-ajax-on');
  256. var off = checkbox.getAttribute('data-ajax-off');
  257. var func = form.getAttribute('data-ajax-func');
  258. if((is && is != null && is == "true") && (on && on != null) && (off && off != null) && (func && func != null)) {
  259. if(window.attachEvent) {
  260. checkbox.attachEvent('onclick', ajax.processCheckboxClick);
  261. } else if(window.addEventListener) {
  262. checkbox.addEventListener('click', ajax.processCheckboxClick, false);
  263. };
  264. };
  265. };
  266. ajax.processCheckboxes = function() {
  267. var checkboxes = document.querySelectorAll('[data-ajax-checkbox]');
  268. for(var key in checkboxes) if(forms.hasOwnProperty(key)) {
  269. var checkbox = checkboxes[key];
  270. ajax.processCheckbox(checkbox);
  271. };
  272. };
  273. ajax.load = function() {
  274. if(!ajax.loaded) {
  275. ajax.loaded = true;
  276. ajax.processTags();
  277. ajax.processForms();
  278. ajax.processCheckboxes();
  279. };
  280. };
  281. if(window.attachEvent) {
  282. window.attachEvent('onload', ajax.load);
  283. } else if(window.addEventListener) {
  284. window.addEventListener('load', ajax.load, false);
  285. };