在调用submit()方法之前更改表单的formData

发布于 2025-01-09 17:59:39 字数 497 浏览 4 评论 0原文

我需要使用 FormData 将一些数据添加到表单中,以便在提交表单时也会发布这条新数据,但我无法让它工作。请注意,我不想使用 ajax 或 fetch 来发送 formData,因为我希望页面在用户单击提交按钮时将用户重定向到不同的页面。

                const myForm = document.querySelector('form');
                myForm.addEventListener('submit', (event) => {
                    event.preventDefault();
                    const formData = new FormData(myForm);
                    formData.append('age', '20');
                    event.target.submit();
                });

I need to add some data to a form using FormData so that when the form is submitted this new piece of data is also posted, but I can't get it working. Note that I do not want to use ajax or fetch to send formData since I want the page to redirect user to a different page when he clicks the submit button.

                const myForm = document.querySelector('form');
                myForm.addEventListener('submit', (event) => {
                    event.preventDefault();
                    const formData = new FormData(myForm);
                    formData.append('age', '20');
                    event.target.submit();
                });

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

放肆 2025-01-16 17:59:39

正如评论中提到的,最好的方法是阻止正常事件,提交您自己的 formData 对象,然后自行重定向。

var form = document.querySelector("form");
form.addEventListener('submit', e => {
    e.preventDefault()
    // build up formdata
    const formData = new FormData(form);
    formData.append("age", '20');
    const request = new XMLHttpRequest();
    request.open("POST", "submitform.php");    

    // redirect on success
    request.addEventListener('load', function( event ) {
      window.location.replace('/my-locaiton')
    });

    // Do whatever needed on error
    request.addEventListener('error', function( event ) {
      console.log('failed request..')
    });   
    
    request.send(formData);
})
<form id="form" action="POST" target="redirect.html">
    <input type="text" value="somtext">
    <input type="submit">
</form>

如果您仍然想让表单完成这项工作,您可以执行类似的操作来阻止该事件,然后再次调度它。
在这种情况下,您需要将隐藏元素添加到表单中:

const form = document.getElementById('form')
const listener = async (e) => {

    // prevent default action.
    e.preventDefault()

    // only run the listener only once.
    form.removeListener('submit', listener)

    // append actual data..
    const ageInput = document.createElement('input')
    ageInput.style.visibility = 'hidden'
    ageInput.setAttribute('name', 'age')
    ageInput.setAttribute('value', '20')
    form.appendChild(ageInput)

    // dispatch event again!
    e.target.dispatchEvent(e)
}

form.addEventListener('submit', listener)

As mentioned in comments the best way to do this was to prevent the normal event, submit your own formData object and then redirect by yourself.

var form = document.querySelector("form");
form.addEventListener('submit', e => {
    e.preventDefault()
    // build up formdata
    const formData = new FormData(form);
    formData.append("age", '20');
    const request = new XMLHttpRequest();
    request.open("POST", "submitform.php");    

    // redirect on success
    request.addEventListener('load', function( event ) {
      window.location.replace('/my-locaiton')
    });

    // Do whatever needed on error
    request.addEventListener('error', function( event ) {
      console.log('failed request..')
    });   
    
    request.send(formData);
})
<form id="form" action="POST" target="redirect.html">
    <input type="text" value="somtext">
    <input type="submit">
</form>

If you still want to let the form do the job you could do something like this to prevent the event and then dispatch it again..
You would need to add hidden elements to the form in this case:

const form = document.getElementById('form')
const listener = async (e) => {

    // prevent default action.
    e.preventDefault()

    // only run the listener only once.
    form.removeListener('submit', listener)

    // append actual data..
    const ageInput = document.createElement('input')
    ageInput.style.visibility = 'hidden'
    ageInput.setAttribute('name', 'age')
    ageInput.setAttribute('value', '20')
    form.appendChild(ageInput)

    // dispatch event again!
    e.target.dispatchEvent(e)
}

form.addEventListener('submit', listener)

む无字情书 2025-01-16 17:59:39

我挣扎了几个小时,最后我想到“为什么我不自己创建另一个表单并尝试提交它?您可以使用 FormData 或 serializeArray() 从以前的表单中提取键和值并将它们附加到新表单中.

let testForm = {'key1': value1, 'key2': value2} // 我想用新表单提交的值

    function add(form, name, value) {

        //Create an input type dynamically.
        var element = document.createElement("input");
        //Assign different attributes to the element.
        element.setAttribute("value", value);
        element.setAttribute("name", name);

        //Append the element in page (in span).
        form.appendChild(element);
    }

    let myForm = document.createElement('form');

    for (const [key, value] of Object.entries(testForm)) {
        console.log(`${key} ${value}`);
        add(myForm, key, value)
    }

    myForm.setAttribute("action", "url")
    myForm.setAttribute("method", "POST")

    document.body.appendChild(myForm)
    myForm.submit();

I was struggling for hours and finally it occurred to me " Why am I not creating another Form myself and try submitting that? You can use FormData or serializeArray() to extract the keys and values from the previous Form and append them to the new form.

let testForm = {'key1': value1, 'key2': value2} // values I want to submit with my new form

    function add(form, name, value) {

        //Create an input type dynamically.
        var element = document.createElement("input");
        //Assign different attributes to the element.
        element.setAttribute("value", value);
        element.setAttribute("name", name);

        //Append the element in page (in span).
        form.appendChild(element);
    }

    let myForm = document.createElement('form');

    for (const [key, value] of Object.entries(testForm)) {
        console.log(`${key} ${value}`);
        add(myForm, key, value)
    }

    myForm.setAttribute("action", "url")
    myForm.setAttribute("method", "POST")

    document.body.appendChild(myForm)
    myForm.submit();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文