Add the option to use FormData to encode the form elements #153

Merged
BehindTheMath merged 4 commits from feature/form-data into master 2018-04-29 14:05:23 -05:00
3 changed files with 51 additions and 5 deletions
Showing only changes of commit 8c8787bac5 - Show all commits

View File

@@ -31,6 +31,22 @@ var formAction = function(el, event) {
event.preventDefault()
if (el.enctype === "multipart/form-data") {
options.requestOptions.formData = new FormData(el)
}
else {
options.requestOptions.requestParams = parseFormElements(el)
}
el.setAttribute(attrState, "submit")
options.triggerElement = el
this.loadUrl(virtLinkElement.href, options)
}
function parseFormElements(el) {
var requestParams = []
robinnorth commented 2018-04-27 03:50:06 -05:00 (Migrated from github.com)
Review

You can remove requestParams: [] from line 19 now, as this makes that initialisation redundant.

You can remove `requestParams: []` from line 19 now, as this makes that initialisation redundant.
BehindTheMath commented 2018-04-27 08:46:32 -05:00 (Migrated from github.com)
Review

Fixed.

Fixed.
for (var elementKey in el.elements) {
if (Number.isNaN(Number(elementKey))) {
continue;
@@ -62,7 +78,7 @@ var formAction = function(el, event) {
}
for (var j = 0; j < values.length; j++) {
options.requestOptions.requestParams.push({
requestParams.push({
name: encodeURIComponent(element.name),
value: encodeURIComponent(values[j])
})
@@ -71,10 +87,7 @@ var formAction = function(el, event) {
}
}
el.setAttribute(attrState, "submit")
options.triggerElement = el
this.loadUrl(virtLinkElement.href, options)
return requestParams
}
function checkIfShouldAbort(virtLinkElement, options) {

View File

@@ -51,6 +51,9 @@ module.exports = function(location, options, callback) {
break
}
}
else if (requestOptions.formData) {
requestPayload = requestOptions.formData
}
// Add a timestamp as part of the query string if cache busting is enabled
if (options.cacheBust) {

View File

@@ -152,3 +152,33 @@ tape("test form elements parsed correctly", function(t) {
t.end()
})
tape("test form.enctype=\"multipart/form-data\"", function(t) {
t.plan(4)
var form = document.createElement("form")
form.enctype = "multipart/form-data"
var input = document.createElement("input")
input.name = "input"
input.value = "value"
form.appendChild(input)
var pjax = {
options: {},
loadUrl: function(href, options) {
t.equals(options.requestOptions.requestParams.length, 0, "form elements not parsed manually")
t.true(options.requestOptions.formData instanceof FormData, "requestOptions.formData is a FormData")
t.equals(Array.from(options.requestOptions.formData.entries()).length, 1, "correct number of FormData elements")
t.equals(options.requestOptions.formData.get("input"), "value", "FormData element value set correctly")
}
}
attachForm.call(pjax, form)
form.action = window.location.protocol + "//" + window.location.host + "/internal"
trigger(form, "submit")
// see loadUrl defined above
t.end()
})