简体   繁体   English

使用纯JavaScript创建,附加和提交表单

[英]Create, append and submit form using pure JavaScript

I'm trying to implement onclick function, which send parameters using POST method. 我正在尝试实现onclick函数,它使用POST方法发送参数。 I need this function to reload the page, what makes me to use some other way than AJAX. 我需要这个函数来重新加载页面,是什么让我使用其他方式而不是AJAX。 I have a function to do this, but this function uses jQuery. 我有一个函数来执行此操作,但此函数使用jQuery。 Now I need to "port it" to pure JavaScript. 现在我需要将它“移植”到纯JavaScript。

jQuery function: jQuery函数:

function domainRemoveConfirmation(id, url) {
    //trick to send javascript redirect with post data
    var form = $('<form action="' + url + '" method="post" hidden="true">' +
              '<input type="text" name="domainId" value="'+ id + '" />' +
              '</form>');
    $('body').append(form);
    $(form).submit();
}

I look for the equivalent function in pure JavaScript, I need to create element (form with input fields), append it and submit it. 我在纯JavaScript中寻找等效函数,我需要创建元素(带有输入字段的表单),附加它并提交它。

Thanks in advance! 提前致谢!

Here you go: 干得好:

function domainRemoveConfirmation(id, url){
    var myForm = document.createElement('form');
    myForm.setAttribute('action', url);
    myForm.setAttribute('method', 'post');
    myForm.setAttribute('hidden', 'true');
    var myInput = document.createElement('input');
    myInput.setAttribute('type', 'text');
    myInput.setAttribute('name', 'domainId');
    myInput.setAttribute('value', id);
    myForm.appendChild(myInput);
    document.body.appendChild(myForm);
    myForm.submit();
};
var form = '<form name="myform" action="' + url + '" method="post" hidden="true">' +
          '<input type="text" name="domainId" value="'+ id + '" />' +
          '</form>';
document.body.innerHTML += form;
document.forms.myform.submit();

var f = document.createElement("form");
f.setAttribute('method',"post");
f.setAttribute('hidden',"true");
f.setAttribute('name',"myform");
f.setAttribute('action',url);

var i = document.createElement("input"); //input element, text
i.setAttribute('type',"text");
i.setAttribute('name',"domainId");
i.setAttribute('value', id);

f.appendChild(i);


document.getElementsByTagName('body')[0].appendChild(f);

document.forms.myform.submit();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM