Created
October 29, 2016 13:54
-
-
Save MikhailRoot/00c0f297bfcb3ffe2cbcb2cf0877ebcc to your computer and use it in GitHub Desktop.
AngularJS $http service tuning for Wordpress
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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