From d688f5947986853148159b9c06d3c40e10904f20 Mon Sep 17 00:00:00 2001 From: guanbo Date: Sun, 19 Jan 2014 21:17:15 +0800 Subject: [PATCH] Fixed: format multilevel json to querystring correctly --- src/ng/http.js | 46 ++++++++++++++++++++++++++++----------------- test/ng/httpSpec.js | 2 +- 2 files changed, 30 insertions(+), 18 deletions(-) diff --git a/src/ng/http.js b/src/ng/http.js index f20d54fd60db..11b08b017891 100644 --- a/src/ng/http.js +++ b/src/ng/http.js @@ -1009,25 +1009,37 @@ function $HttpProvider() { } } - - function buildUrl(url, params) { - if (!params) return url; - var parts = []; - forEachSorted(params, function(value, key) { - if (value === null || isUndefined(value)) return; - if (!isArray(value)) value = [value]; - - forEach(value, function(v) { - if (isObject(v)) { - v = toJson(v); - } - parts.push(encodeUriQuery(key) + '=' + - encodeUriQuery(v)); - }); + function is(type, obj) { + var clas = Object.prototype.toString.call(obj).slice(8, -1); + return obj !== undefined && obj !== null && clas === type; + } + + function toQueryString(params, parts, pk) { + forEachSorted(params, function(value, key) { + if (value === null || value === undefined) return; + if (pk) key = pk+'['+key+']'; + if (is('Array',value)) { + forEach(value, function(v,i) { + if(is('Object', v)){ + key = key+'['+i+']'; + toQueryString(v, parts, key); + } else { + parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(v)); + } }); - return url + ((url.indexOf('?') == -1) ? '?' : '&') + parts.join('&'); + return; + } else if (is('Object',value)) { + return toQueryString(value, parts, key); } + parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(value)); + }); + } - + function buildUrl(url, params) { + if (!params) return url; + var parts = []; + toQueryString(params, parts); + return url + ((url.indexOf('?') == -1) ? '?' : '&') + parts.join('&'); + } }]; } diff --git a/test/ng/httpSpec.js b/test/ng/httpSpec.js index a0417d9ad99c..37768519b029 100644 --- a/test/ng/httpSpec.js +++ b/test/ng/httpSpec.js @@ -432,7 +432,7 @@ describe('$http', function() { it('should jsonify objects in params map', inject(function($httpBackend, $http) { - $httpBackend.expect('GET', '/url?a=1&b=%7B%22c%22:3%7D').respond(''); + $httpBackend.expect('GET', '/url?a=1&b%5Bc%5D=3').respond(''); $http({url: '/url', params: {a:1, b:{c:3}}, method: 'GET'}); }));