97 lines
2.6 KiB
JavaScript
97 lines
2.6 KiB
JavaScript
/** Form collect + application/x-www-form-urlencoded. */
|
|
|
|
function bareSummonEncodeForm(pairs) {
|
|
var out = []
|
|
for (var i = 0; i < pairs.length; i++) {
|
|
var n = pairs[i].name
|
|
var v = pairs[i].value
|
|
if (!n) continue
|
|
out.push(
|
|
encodeURIComponent(n) + '=' + encodeURIComponent(v == null ? '' : v)
|
|
)
|
|
}
|
|
return out.join('&')
|
|
}
|
|
|
|
function bareSummonCollectForm(formNode) {
|
|
var pairs = []
|
|
var method = (
|
|
(formNode.attrs && formNode.attrs.method) ||
|
|
'get'
|
|
).toLowerCase()
|
|
var action = (formNode.attrs && formNode.attrs.action) || ''
|
|
function walk(n) {
|
|
if (!n || n.type !== 'element') return
|
|
var name = n.name
|
|
var a = n.attrs || {}
|
|
if (
|
|
(name === 'input' || name === 'textarea' || name === 'select') &&
|
|
a.name
|
|
) {
|
|
var typ = (a.type || 'text').toLowerCase()
|
|
if (
|
|
typ === 'submit' ||
|
|
typ === 'button' ||
|
|
typ === 'image' ||
|
|
typ === 'file'
|
|
)
|
|
return
|
|
if (
|
|
(typ === 'checkbox' || typ === 'radio') &&
|
|
a.checked == null &&
|
|
a.value === undefined
|
|
) {
|
|
/* still include if checked attr present */
|
|
}
|
|
if (typ === 'checkbox' && a.checked === undefined && !('checked' in a))
|
|
return
|
|
if (typ === 'radio' && !('checked' in a)) return
|
|
var val = a.value
|
|
if (name === 'textarea') val = bareSummonTextContent(n)
|
|
if (name === 'select') {
|
|
val = a.value || ''
|
|
var ch = n.children || []
|
|
for (var i = 0; i < ch.length; i++) {
|
|
if (ch[i].name === 'option' && 'selected' in (ch[i].attrs || {})) {
|
|
val =
|
|
ch[i].attrs.value != null
|
|
? ch[i].attrs.value
|
|
: bareSummonTextContent(ch[i])
|
|
}
|
|
}
|
|
}
|
|
pairs.push({ name: a.name, value: val == null ? '' : String(val) })
|
|
}
|
|
var kids = n.children || []
|
|
for (var k = 0; k < kids.length; k++) walk(kids[k])
|
|
}
|
|
walk(formNode)
|
|
return {
|
|
method: method === 'post' ? 'POST' : 'GET',
|
|
action: action,
|
|
pairs: pairs
|
|
}
|
|
}
|
|
|
|
function bareSummonSubmitUrl(form, pageUrl) {
|
|
var spec =
|
|
typeof form.method === 'string' ? form : bareSummonCollectForm(form)
|
|
var action = bareSummonResolveUrl(spec.action || pageUrl, pageUrl)
|
|
if (!action) return null
|
|
var q = bareSummonEncodeForm(spec.pairs)
|
|
if (spec.method === 'GET') {
|
|
var href = action.href.split('#')[0].split('?')[0]
|
|
return {
|
|
method: 'GET',
|
|
url: href + (q ? '?' + q : ''),
|
|
body: null
|
|
}
|
|
}
|
|
return {
|
|
method: 'POST',
|
|
url: action.href,
|
|
body: q,
|
|
headers: { 'content-type': 'application/x-www-form-urlencoded' }
|
|
}
|
|
}
|