设置HTML表单的自定义enctype?

时间:2019-09-06 14:20:56

标签: html forms serialization

说我有一个HTML表单:

<form action="/whatever" enctype="application/x-custom" method="POST">
<input type="hidden" name="foo" value="bar"/>
<button type="submit">Go!</button>
</form>

是否可以为浏览器提供自定义enctype算法?假设算法为:

<script>
function algo(/** HTMLFormElement */form) {
return Array
    .from(form.elements)
    .filter(e => e.type === 'hidden')
    .map(e => e.name.length + ';' + e.value.length + ';' + e.name + e.value)
    .join("\n");
}
</script>

有没有一种方法可以将该算法“绑定”到表单,以便浏览器 跟随它以序列化表单数据,并使用Content-Type: application/x-custom和算法的结果发送表单请求作为请求主体?

我不是在寻找“使用XMLHttpRequest”的答案,我只是在寻找具有自定义表单数据序列化功能的基于浏览器的表单提交。

1 个答案:

答案 0 :(得分:0)

否,不幸的是,如果要以自定义格式发送数据,则必须通过AJAX发送。我不得不做几次,这一点都不小。您的代码将因<input type="checkbox><select>disabled输入和许多其他输入而失败。

就发送数据而言,假设设法正确处理数据,您希望通过获取来发送:

/**
 * @param {HTMLElement} form
 */
function algo(form) {
    return Array
        .from(form.elements)
        .filter(e => e.type === 'hidden')
        .map(e => e.name.length + ';' + e.value.length + ';' + e.name + e.value)
        .join("\n");
}
/**
 * 
 * @param {HTMLFormElement} form
 */
async function postData(form) {

    // Default options are marked with *
    const response = await fetch(form.action, {
        method: 'POST',
        cache: 'no-cache',
        headers: {
            'Content-Type': 'application/x-custom',
        },
        redirect: 'follow',
        body: algo(form)
    });
    window.history.pushState(null, "", form.action);
    // this is nasty, but emulates form response nicely
    // do not actually do this
    document.open();
    document.write(await response.text());
    document.close();
}

或者,有一个服务器端处理程序将接收到的表单数据转换为正确的格式。