Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
AngularJS $http service tuning for Wordpress
/**
* Created by Mikhail.root on 22.02.2016. originaly from http://habrahabr.ru/post/181009/
* Fixed encoding of JS Date objects
*/
(function () {
'use strict';
angular.extend(angular, {toParam: toParam})
.module('YourAppModuleNameHere') // set it to your app module name!
.config(['$httpProvider',function ($httpProvider) {
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
$httpProvider.defaults.transformRequest = function (data) {
return angular.isObject(data) && String(data) !== '[object File]' ? angular.toParam(data) : data;
};
}
]);
/**
* Преобразует объект, массив или массив объектов в строку,
* которая соответствует формату передачи данных через url
* Почти эквивалент [url]http://api.jquery.com/jQuery.param/[/url]
* Источник [url]http://stackoverflow.com/questions/1714786/querystring-encoding-of-a-javascript-object/1714899#1714899[/url]
*
* @param object
* @param [prefix]
* @returns {string}
*/
function toParam(object, prefix) {
var stack = [];
var value;
var key;
for (key in object) {
value = object[key];
key = prefix ? prefix + '[' + key + ']' : key;
if (value === null) {
value = encodeURIComponent(key) + '=';
} else if (typeof( value ) !== 'object') {
value = encodeURIComponent(key) + '=' + encodeURIComponent(value);
} else if (value instanceof Date) {
value = encodeURIComponent(key) + '=' + encodeURIComponent(value.toISOString());
} else {
value = toParam(value, key);
}
stack.push(value);
}
return stack.join('&');
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.