Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function hasOwn(o, p) {
- return Object.prototype.hasOwnProperty.call(o, p);
- }
- function log() {
- console.log.apply(console, arguments);
- }
- function typeName(o) {
- return Object.prototype.toString.call(o).slice(8, -1);
- }
- function is(t, o) {
- return t == typeName(o);
- }
- function isObject(o) {
- return is('Object', o);
- }
- function isArray(o) {
- return Array.isArray(o);
- }
- function isObjectOrArray(o) {
- return isObject(o) || isArray(o);
- }
- // Эту функцию из какого-то популярного двига с PHP переписал
- function buildQuery(data, prefix) {
- if (!isObjectOrArray(data)) {
- throw new TypeError("must be an object or an array");
- }
- var r = []
- , k
- , v;
- for (var k in data) {
- if (hasOwn(data, k)) {
- v = data[k];
- k = encodeURIComponent(k);
- k = typeof prefix == 'undefined' ? k : prefix + '[' + k + ']';
- r.push(isObjectOrArray(v) ? buildQuery(v, k) : k + '=' + encodeURIComponent(v))
- }
- }
- return r.join('&');
- }
- function parseReq(req) {
- try {
- return JSON.parse(req.response);
- } catch (e) {
- return req.response;
- }
- }
- function post(url, data) {
- return new Promise(function (resolve, reject) {
- var req = new XMLHttpRequest;
- req.open('POST', url);
- req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
- data = isObject(data) ? buildQuery(data) : data;
- req.onload = function () {
- var res = parseReq(req);
- if (req.status == 200) {
- resolve(res);
- } else {
- reject(res);
- }
- };
- req.onerror = function () {
- reject("Network Error");
- };
- req.send(data);
- });
- }
- // Переходим сюда http://httpbin.org и испытываем
- post('/post', {x: ['foo', 'bar']}).then(function (data) {
- log("Sucess: ", data);
- }, function (err) {
- log("Error: ", err);
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement