Skip to content

Commit 63b93fc

Browse files
committed
Add support for post json body
1 parent eec76fb commit 63b93fc

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

README.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,12 @@ An object containing extra data that should be submitted along with the form.
125125
````
126126
data: { key1: 'value1', key2: 'value2' }
127127
````
128+
### requestFormat
129+
Avaliable value:
130+
* `json` : post request data with json string in post body.
131+
* You may need polyfill `JSON` functionality with old browsers, recommending: https://github.com/douglascrockford/JSON-js/blob/master/json2.js
132+
* `form` : (default) post request body with form http format
133+
128134

129135
### dataType
130136
Expected data type of the response. One of: null, 'xml', 'script', or 'json'. The dataType option provides a means for specifying how the server response should be handled. This maps directly to jQuery's dataType method. The following values are supported:

src/jquery.form.js

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -200,9 +200,10 @@
200200

201201
var elements = [];
202202
var qx, a = this.formToArray(options.semantic, elements, options.filtering);
203+
var optionsData;
203204

204205
if (options.data) {
205-
var optionsData = $.isFunction(options.data) ? options.data(a) : options.data;
206+
optionsData = $.isFunction(options.data) ? options.data(a) : options.data;
206207

207208
options.extraData = optionsData;
208209
qx = $.param(optionsData, traditional);
@@ -232,7 +233,13 @@
232233
if (options.type.toUpperCase() === 'GET') {
233234
options.url += (options.url.indexOf('?') >= 0 ? '&' : '?') + q;
234235
options.data = null; // data is null for 'get'
236+
} else if (options.requestFormat.toLowerCase() === 'json') {
237+
var formData = this.formArrayToJsonData(a);
238+
var jsonData = $.extend({}, formData, traditional);
239+
options.data = JSON.stringify(jsonData);
240+
options.contentType = 'application/json';
235241
} else {
242+
// form-data post
236243
options.data = q; // data is the query string for 'post'
237244
}
238245

@@ -1193,6 +1200,19 @@
11931200
return $.param(this.formToArray(semantic));
11941201
};
11951202

1203+
/**
1204+
* Transform form array data into json object.
1205+
*/
1206+
$.fn.formArrayToJsonData = function (arrayOfData) {
1207+
var result = {};
1208+
1209+
$.each(arrayOfData, function (index, node) {
1210+
result[node.name] = result[node.value];
1211+
});
1212+
1213+
return result;
1214+
};
1215+
11961216
/**
11971217
* Serializes all field elements in the jQuery object into a query string.
11981218
* This method will return a string in the format: name1=value1&name2=value2

0 commit comments

Comments
 (0)