sashomaga

custom ajax

Dec 14th, 2013
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.  var ajax = {};
  2.  
  3. ajax.send = function(url, cb_success, method, data, sync, cb_error) {
  4.     var x = new XMLHttpRequest();
  5.     x.open(method, url, sync);
  6.     x.onreadystatechange = function() {
  7.         if (x.readyState === 4 && x.status === 200) {            
  8.                     cb_success(x.responseText);          
  9.         } else {
  10.         cb_error(x.statusText);
  11.         }
  12.     };
  13.     if (method === 'POST') {
  14.         x.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
  15.     }
  16.     x.send(data)
  17. };
  18.  
  19. ajax.get = function(url, data, cb_success, sync, cb_error) {
  20.     var query = [];
  21.     for (var key in data) {
  22.         query.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]));
  23.     }
  24.     ajax.send(url + '?' + query.join('&'), cb_success, 'GET', null, sync, cb_error);
  25. };
  26.  
  27. ajax.post = function(url, data, cb_success, sync, cb_error) {
  28.     var query = [];
  29.     for (var key in data) {
  30.         query.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]));
  31.     }
  32.     ajax.send(url, cb_success, 'POST', query.join('&'), sync, cb_error);
  33. };
Advertisement
Add Comment
Please, Sign In to add comment