Advertisement
stuppid_bot

Untitled

Sep 8th, 2014
327
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function hasOwn(o, p) {
  2.   return Object.prototype.hasOwnProperty.call(o, p);
  3. }
  4.  
  5. function log() {
  6.   console.log.apply(console, arguments);
  7. }
  8.  
  9. function typeName(o) {
  10.   return Object.prototype.toString.call(o).slice(8, -1);
  11. }
  12.  
  13. function is(t, o) {
  14.   return t == typeName(o);
  15. }
  16.  
  17. function isObject(o) {
  18.   return is('Object', o);
  19. }
  20.  
  21. function isArray(o) {
  22.   return Array.isArray(o);
  23. }
  24.  
  25. function isObjectOrArray(o) {
  26.   return isObject(o) || isArray(o);
  27. }
  28.  
  29. // Эту функцию из какого-то популярного двига с PHP переписал
  30. function buildQuery(data, prefix) {
  31.   if (!isObjectOrArray(data)) {
  32.     throw new TypeError("must be an object or an array");
  33.   }
  34.   var r = []
  35.     , k
  36.     , v;
  37.   for (var k in data) {
  38.     if (hasOwn(data, k)) {
  39.       v = data[k];
  40.       k = encodeURIComponent(k);
  41.       k = typeof prefix == 'undefined' ? k : prefix + '[' + k + ']';
  42.       r.push(isObjectOrArray(v) ? buildQuery(v, k) : k + '=' + encodeURIComponent(v))
  43.     }
  44.   }
  45.   return r.join('&');
  46. }
  47.  
  48. function parseReq(req) {
  49.   try {
  50.     return JSON.parse(req.response);
  51.   } catch (e) {
  52.     return req.response;
  53.   }
  54. }
  55.  
  56. function post(url, data) {
  57.   return new Promise(function (resolve, reject) {
  58.     var req = new XMLHttpRequest;
  59.     req.open('POST', url);
  60.     req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  61.     data = isObject(data) ? buildQuery(data) : data;
  62.     req.onload = function () {
  63.       var res = parseReq(req);
  64.       if (req.status == 200) {
  65.         resolve(res);
  66.       } else {
  67.         reject(res);
  68.       }
  69.     };
  70.     req.onerror = function () {
  71.       reject("Network Error");
  72.     };
  73.     req.send(data);
  74.   });
  75. }
  76.  
  77. // Переходим сюда http://httpbin.org и испытываем
  78. post('/post', {x: ['foo', 'bar']}).then(function (data) {
  79.   log("Sucess: ", data);
  80. }, function (err) {
  81.   log("Error: ", err);
  82. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement