ajax.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  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, multipart) {
  28. if(async === undefined) {
  29. async = true;
  30. };
  31. if(multipart === undefined) {
  32. multipart = false;
  33. };
  34. var a = ajax.create();
  35. a.open(method, url, async);
  36. a.onreadystatechange = function() {
  37. // a.readyState:
  38. // 0 - UNSENT
  39. // 1 - OPENED
  40. // 2 - HEADERS_RECEIVED
  41. // 3 - LOADING
  42. // 4 - DONE
  43. callback(method, data, a.readyState, a.status, a.responseText);
  44. };
  45. if(method == 'PUT' || method == 'POST') {
  46. if(!multipart) {
  47. a.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
  48. };
  49. };
  50. a.send(data);
  51. };
  52. ajax.del = function(url, data, callback, async) {
  53. var query = [];
  54. for(var key in data) {
  55. query.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]));
  56. };
  57. ajax.send(url + (query.length ? '?' + query.join('&') : ''), callback, 'DELETE', null, async);
  58. };
  59. ajax.delJSON = function(url, data, callbackSuccess, callbackError, async) {
  60. ajax.del(url, data, function(method, data, readyState, status, responseText) {
  61. if(readyState == 4) {
  62. if(status == 200) {
  63. try {
  64. var r = JSON.parse(responseText);
  65. if(callbackSuccess) {
  66. callbackSuccess(method, data, readyState, status, r);
  67. };
  68. } catch(e) {
  69. if(callbackError) {
  70. callbackError(method, data, readyState, status, e);
  71. };
  72. };
  73. } else {
  74. if(callbackError) {
  75. var e = new AjaxErrorBadStatusCode('Bad status code '+status);
  76. callbackError(method, data, readyState, status, e);
  77. };
  78. };
  79. };
  80. }, async);
  81. };
  82. ajax.get = function(url, data, callback, async) {
  83. var query = [];
  84. for(var key in data) {
  85. query.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]));
  86. };
  87. ajax.send(url + (query.length ? '?' + query.join('&') : ''), callback, 'GET', null, async);
  88. };
  89. ajax.getJSON = function(url, data, callbackSuccess, callbackError, async) {
  90. ajax.get(url, data, function(method, data, readyState, status, responseText) {
  91. if(readyState == 4) {
  92. if(status == 200) {
  93. try {
  94. var r = JSON.parse(responseText);
  95. if(callbackSuccess) {
  96. callbackSuccess(method, data, readyState, status, r);
  97. };
  98. } catch(e) {
  99. if(callbackError) {
  100. callbackError(method, data, readyState, status, e);
  101. };
  102. };
  103. } else {
  104. if(callbackError) {
  105. var e = new AjaxErrorBadStatusCode('Bad status code '+status);
  106. callbackError(method, data, readyState, status, e);
  107. };
  108. };
  109. };
  110. }, async);
  111. };
  112. ajax.put = function(url, data, callback, async, multipart) {
  113. if(multipart) {
  114. ajax.send(url, callback, 'PUT', data, async, multipart);
  115. } else {
  116. var query = [];
  117. for (var key in data) {
  118. query.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]));
  119. };
  120. ajax.send(url, callback, 'PUT', query.join('&'), async, multipart);
  121. };
  122. };
  123. ajax.putJSON = function(url, data, callbackSuccess, callbackError, async, multipart) {
  124. ajax.put(url, data, function(method, data, readyState, status, responseText) {
  125. if(readyState == 4) {
  126. if(status == 200) {
  127. try {
  128. var r = JSON.parse(responseText);
  129. if(callbackSuccess) {
  130. callbackSuccess(method, data, readyState, status, r);
  131. };
  132. } catch(e) {
  133. if(callbackError) {
  134. callbackError(method, data, readyState, status, e);
  135. };
  136. };
  137. } else {
  138. if(callbackError) {
  139. var e = new AjaxErrorBadStatusCode('Bad status code '+status);
  140. callbackError(method, data, readyState, status, e);
  141. };
  142. };
  143. };
  144. }, async, multipart);
  145. };
  146. ajax.post = function(url, data, callback, async, multipart) {
  147. if(multipart) {
  148. ajax.send(url, callback, 'POST', data, async, multipart);
  149. } else {
  150. var query = [];
  151. for (var key in data) {
  152. query.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]));
  153. };
  154. ajax.send(url, callback, 'POST', query.join('&'), async, multipart);
  155. };
  156. };
  157. ajax.postJSON = function(url, data, callbackSuccess, callbackError, async, multipart) {
  158. ajax.post(url, data, function(method, data, readyState, status, responseText) {
  159. if(readyState == 4) {
  160. if(status == 200) {
  161. try {
  162. var r = JSON.parse(responseText);
  163. if(callbackSuccess) {
  164. callbackSuccess(method, data, readyState, status, r);
  165. };
  166. } catch(e) {
  167. if(callbackError) {
  168. callbackError(method, data, readyState, status, e);
  169. };
  170. };
  171. } else {
  172. if(callbackError) {
  173. var e = new AjaxErrorBadStatusCode('Bad status code '+status);
  174. callbackError(method, data, readyState, status, e);
  175. };
  176. };
  177. };
  178. }, async, multipart);
  179. };
  180. ajax.loadTag = function(tag, url, func, field) {
  181. if((typeof window[func] === 'function') || field != null) {
  182. if(!!!tag.className.match(new RegExp('(\\s|^)loading(\\s|$)'))) {
  183. tag.className += " loading";
  184. ajax.getJSON(url, {}, function(method, data, readyState, status, responseData) {
  185. try {
  186. if(typeof window[func] === 'function') {
  187. var html = window[func](tag, responseData);
  188. tag.innerHTML = html;
  189. } else if(field != null) {
  190. tag.innerHTML = responseData[field];
  191. };
  192. } catch(e) {
  193. console.log('ajax.loadTag', 'e', e);
  194. };
  195. tag.className = tag.className.replace(new RegExp('(\\s|^)loading(\\s|$)'), ' ').trim();
  196. }, function(method, data, readyState, status, responseData) {
  197. tag.className = tag.className.replace(new RegExp('(\\s|^)loading(\\s|$)'), ' ').trim();
  198. });
  199. };
  200. };
  201. };
  202. ajax.processTag = function(tag) {
  203. var get = tag.getAttribute('data-ajax-get');
  204. var func = tag.getAttribute('data-ajax-func');
  205. var field = tag.getAttribute('data-ajax-field');
  206. var delay = tag.getAttribute('data-ajax-delay');
  207. if((get && get != null) && ((func && func != null) || (field && field != null))) {
  208. if(delay == null) {
  209. ajax.loadTag(tag, get, func, field);
  210. } else {
  211. setTimeout(function() {
  212. ajax.loadTag(tag, get, func, field);
  213. }, delay);
  214. };
  215. };
  216. };
  217. ajax.processTags = function() {
  218. var tags = document.querySelectorAll('[data-ajax-get]');
  219. for(var key in tags) if(tags.hasOwnProperty(key)) {
  220. var tag = tags[key];
  221. ajax.processTag(tag);
  222. };
  223. };
  224. ajax.reloadTag = function(tag) {
  225. ajax.processTag(tag);
  226. };
  227. ajax.reloadTagById = function(id) {
  228. var tag = document.getElementById(id)
  229. if(tag != null) {
  230. ajax.reloadTag(tag);
  231. };
  232. };
  233. ajax.processFormSubmit = function(event) {
  234. if(!event) var event = window.event;
  235. event.preventDefault();
  236. var form = event.target;
  237. var func = form.getAttribute('data-ajax-func');
  238. var put = form.getAttribute('data-put');
  239. if(func && func != null && typeof window[func] === 'function') {
  240. if(!!!form.className.match(new RegExp('(\\s|^)loading(\\s|$)'))) {
  241. form.className += " loading";
  242. var data = null;
  243. var inputs = form.querySelectorAll("input,select,textarea");
  244. var files = form.querySelectorAll("input[type=file]");
  245. var multipart = files.length > 0;
  246. if(!multipart) {
  247. data = {};
  248. var inputs = form.querySelectorAll("input,select,textarea");
  249. for(var i=0,m=inputs.length-1; i<=m; i++) {
  250. data[inputs[i].name] = inputs[i].value;
  251. };
  252. } else {
  253. data = new FormData();
  254. var inputs = form.querySelectorAll("input,select,textarea");
  255. for(var i=0,m=inputs.length-1; i<=m; i++) {
  256. if(inputs[i].type != 'file') {
  257. data.append(inputs[i].name, inputs[i].value);
  258. } else {
  259. if(!multipart) {
  260. multipart = true;
  261. };
  262. };
  263. };
  264. var files = form.querySelectorAll("input[type=file]");
  265. for(var i=0,m=files.length-1; i<=m; i++) {
  266. for(var j=0,k=files[i].files.length-1; j<=k; j++) {
  267. data.append(files[i].name, files[i].files[j]);
  268. };
  269. };
  270. };
  271. var ajaxFunc = ajax.get;
  272. if(form.method == "post") { ajaxFunc = ajax.post; };
  273. if(put && put != null && put == "true") { ajaxFunc = ajax.put; };
  274. ajaxFunc(form.action, data, function(method, data, readyState, status, responseText) {
  275. if(readyState == 4) {
  276. var error = (status != 200);
  277. var responseData = responseText;
  278. try {
  279. var responseData = JSON.parse(responseText);
  280. } catch(e) {
  281. console.log('ajax.processFormSubmit', 'e', e);
  282. };
  283. try {
  284. window[func](form, responseData, error, status);
  285. } catch(e) {
  286. console.log('ajax.processFormSubmit', 'e', e);
  287. };
  288. form.className = form.className.replace(new RegExp('(\\s|^)loading(\\s|$)'), ' ').trim();
  289. };
  290. }, true, multipart);
  291. };
  292. };
  293. };
  294. ajax.processForm = function(form) {
  295. var is = form.getAttribute('data-ajax-form');
  296. var func = form.getAttribute('data-ajax-func');
  297. if((is && is != null && is == "true") && (func && func != null)) {
  298. if(window.attachEvent) {
  299. form.attachEvent('onsubmit', ajax.processFormSubmit);
  300. } else if(window.addEventListener) {
  301. form.addEventListener('submit', ajax.processFormSubmit, false);
  302. };
  303. };
  304. };
  305. ajax.processForms = function() {
  306. var forms = document.querySelectorAll('[data-ajax-form]');
  307. for(var key in forms) if(forms.hasOwnProperty(key)) {
  308. var form = forms[key];
  309. ajax.processForm(form);
  310. };
  311. };
  312. ajax.processCheckboxClick = function(event) {
  313. if(!event) var event = window.event;
  314. var checkbox = event.target;
  315. var on = checkbox.getAttribute('data-ajax-on');
  316. var off = checkbox.getAttribute('data-ajax-off');
  317. var func = checkbox.getAttribute('data-ajax-func');
  318. var box = checkbox.parentNode;
  319. if(!!box.className.match(new RegExp('(\\s|^)loading(\\s|$)'))) {
  320. event.preventDefault();
  321. event.stopPropagation();
  322. return false;
  323. };
  324. box.className += " loading";
  325. ajax.post(checkbox.checked ? on : off, {}, function(method, data, readyState, status, responseText) {
  326. if(readyState == 4) {
  327. var error = (status != 200);
  328. var responseData = responseText;
  329. try {
  330. var responseData = JSON.parse(responseText);
  331. } catch(e) {
  332. console.log('ajax.processCheckboxClick', 'e', e);
  333. };
  334. try {
  335. window[func](checkbox, responseData, error, status);
  336. } catch(e) {
  337. console.log('ajax.processCheckboxClick', 'e', e);
  338. };
  339. if(error) {
  340. checkbox.checked = !checkbox.checked;
  341. };
  342. box.className = box.className.replace(new RegExp('(\\s|^)loading(\\s|$)'), ' ').trim();
  343. };
  344. });
  345. return true;
  346. };
  347. ajax.processCheckbox = function(checkbox) {
  348. var is = checkbox.getAttribute('data-ajax-checkbox');
  349. var on = checkbox.getAttribute('data-ajax-on');
  350. var off = checkbox.getAttribute('data-ajax-off');
  351. var func = checkbox.getAttribute('data-ajax-func');
  352. if((is && is != null && is == "true") && (on && on != null) && (off && off != null) && (func && func != null)) {
  353. if(window.attachEvent) {
  354. checkbox.attachEvent('onclick', ajax.processCheckboxClick);
  355. } else if(window.addEventListener) {
  356. checkbox.addEventListener('click', ajax.processCheckboxClick, false);
  357. };
  358. };
  359. };
  360. ajax.processCheckboxes = function() {
  361. var checkboxes = document.querySelectorAll('[data-ajax-checkbox]');
  362. for(var key in checkboxes) if(checkboxes.hasOwnProperty(key)) {
  363. var checkbox = checkboxes[key];
  364. ajax.processCheckbox(checkbox);
  365. };
  366. };
  367. ajax.load = function() {
  368. if(!ajax.loaded) {
  369. ajax.loaded = true;
  370. ajax.processTags();
  371. ajax.processForms();
  372. ajax.processCheckboxes();
  373. };
  374. };
  375. if(window.attachEvent) {
  376. window.attachEvent('onload', ajax.load);
  377. } else if(window.addEventListener) {
  378. window.addEventListener('load', ajax.load, false);
  379. };