From 4c1da6f78b7c37480c84a926fb3c90320ec29f53 Mon Sep 17 00:00:00 2001 From: Anton Romanov Date: Fri, 17 Apr 2015 17:26:21 -0700 Subject: [PATCH] Allow to encode post/get params with json.stirngify and specify own content-type --- data/js/tomahawk.js | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/data/js/tomahawk.js b/data/js/tomahawk.js index dd02c56b8..8332ea23f 100644 --- a/data/js/tomahawk.js +++ b/data/js/tomahawk.js @@ -494,6 +494,7 @@ Tomahawk.ajax = function(url, settings) { settings.type = settings.type || settings.method || 'get'; settings.method = settings.type; + settings.dataEncodingFormat = settings.dataEncodingFormat || 'form'; if (settings.data) { var formEncode = function(obj) { @@ -508,14 +509,28 @@ Tomahawk.ajax = function(url, settings) { return str.join("&"); }; + if (typeof settings.data === 'object') { + if (settings.dataEncodingFormat == 'form') { + settings.data = formEncode(settings.data); + settings.contentType = settings.contentType || 'application/x-www-form-urlencoded'; + } else if (settings.dataEncodingFormat == 'json') { + settings.data = JSON.stringify(settings.data); + settings.contentType = settings.contentType || 'application/json'; + } else { + throw new Error("Tomahawk.ajax: unknown dataEncodingFormat requested: " + settings.dataEncodingFormat); + } + } else { + throw new Error("Tomahawk.ajax: data should be either object or string"); + } if (settings.type.toLowerCase() === 'get') { - settings.url += '?' + formEncode(settings.data); + settings.url += '?' + settings.data; delete settings.data; } else { settings.headers = settings.headers || {}; - settings.headers['Content-Type'] = 'application/x-www-form-urlencoded'; - settings.data = formEncode(settings.data); + if (!settings.headers.hasOwnProperty('Content-Type')) { + settings.headers['Content-Type'] = settings.contentType; + } } }