diff --git a/core-xhr.html b/core-xhr.html
index ea22804..8415606 100644
--- a/core-xhr.html
+++ b/core-xhr.html
@@ -71,21 +71,36 @@
}
return xhr;
},
-
+
toQueryString: function(params) {
+ var r = this.encodeObject(params, '');
+ return r.join('&');
+ },
+
+ encodeKeyValuePair : function(n, v){
+ return v == null ? n : (n + '=' + encodeURIComponent(v));
+ },
+
+ encodeObject : function(obj, prefix){
var r = [];
- for (var n in params) {
- var v = params[n];
- n = encodeURIComponent(n);
- r.push(v == null ? n : (n + '=' + encodeURIComponent(v)));
+ prefix = prefix || '';
+ for (var n in obj) {
+ var v = obj[n];
+ if(typeof v === 'object') {
+ n = prefix + encodeURIComponent('[' + n + ']');
+ r = r.concat(this.encodeObject(v, n));
+ } else {
+ n = prefix + encodeURIComponent(prefix ? '[' + n + ']' : n);
+ r.push(this.encodeKeyValuePair(n, v));
+ }
}
- return r.join('&');
+ return r;
},
isBodyMethod: function(method) {
return this.bodyMethods[(method || '').toUpperCase()];
},
-
+
bodyMethods: {
POST: 1,
PUT: 1,
@@ -112,5 +127,5 @@
});
-
+
diff --git a/test/core-ajax.html b/test/core-ajax.html
index ea21f09..7d8689e 100644
--- a/test/core-ajax.html
+++ b/test/core-ajax.html
@@ -280,6 +280,56 @@
});
});
});
+ suite('params', function() {
+ suiteSetup(function () {
+ ajax.url = "http://example.com/";
+ });
+ test('should write single level object param to query string correctly.', function (done) {
+ async.series([
+ function (cb) {
+ ajax.params = '{"s": "bar", "t":"foo"}';
+ ajax.method = 'POST';
+ ajax.body = '';
+ cb();
+ },
+ animationFrameFlush,
+ function (cb) {
+ assert.equal(requests[0].requestBody, 's=bar&t=foo');
+ cb();
+ }
+ ], done);
+ });
+ test('should write 2 level object param to query string correctly.', function (done) {
+ async.series([
+ function (cb) {
+ ajax.params = '{"s": { "t": "bar", "u": "foo"}}';
+ ajax.method = 'POST';
+ ajax.body = '';
+ cb();
+ },
+ animationFrameFlush,
+ function (cb) {
+ assert.equal(requests[0].requestBody, '%5Bs%5D%5Bt%5D=bar&%5Bs%5D%5Bu%5D=foo');
+ cb();
+ }
+ ], done);
+ });
+ test('should write multi level object param to query string correctly.', function (done) {
+ async.series([
+ function (cb) {
+ ajax.params = '{"s": { "t": {"v": "bar" }, "u": "foo"}}';
+ ajax.method = 'POST';
+ ajax.body = '';
+ cb();
+ },
+ animationFrameFlush,
+ function (cb) {
+ assert.equal(requests[0].requestBody, '%5Bs%5D%5Bt%5D%5Bv%5D=bar&%5Bs%5D%5Bu%5D=foo');
+ cb();
+ }
+ ], done);
+ });
+ });
});