37

我正在尝试创建一个表单并立即使用 javascript 提交它,但我无法弄清楚我做错了什么。这是我的代码:

function autoLogIn(un, pw) {
var form = document.createElement("form");
document.body.appendChild(form);
form.method = "POST";
form.action = "login.php";
var element1 = document.createElement("<INPUT NAME='un' TYPE='hidden' VALUE='"+un+"'>");  
 form.appendChild(element1);
var element2 = document.createElement("<INPUT NAME='pw' TYPE='hidden' VALUE='"+pw+"'>"); 
form.appendChild(element2);
form.submit();
}
4

4 回答 4

103

问题是 createElement 不接受 HTML。它接受一个标记名并返回一个 DOM 元素。然后,您可以将此元素的 value 属性设置为您需要的值。

function autoLogIn(un, pw) {
    var form = document.createElement("form");
    var element1 = document.createElement("input"); 
    var element2 = document.createElement("input");  

    form.method = "POST";
    form.action = "login.php";   

    element1.value=un;
    element1.name="un";
    form.appendChild(element1);  

    element2.value=pw;
    element2.name="pw";
    form.appendChild(element2);

    document.body.appendChild(form);

    form.submit();
}
于 2012-10-21T20:28:12.953 回答
6

Modified code: jsfiddle.

function autoLogIn(un, pw) {
   var form = document.createElement("form");
   document.body.appendChild(form);
   form.method = "POST";
   form.action = "login.php";
   var element1 = document.createElement("INPUT");         
    element1.name="un"
    element1.value = un;
    element1.type = 'hidden'
    form.appendChild(element1);
    var element2 = document.createElement("INPUT");         
    element2.name="pw"
    element2.value = pw;
    element2.type = 'hidden'
    form.appendChild(element2);
    form.submit();
}
于 2012-10-21T20:32:59.477 回答
2

您也可以进行 Saurabh Chauhan 响应,但不将动态元素添加到主体此解决方案是所有动态解决方案。

    var myform = document.createElement("form");
    myform.action = "myForm.aspx";
    myform.method = "post";


    product = document.createElement("input");
    product.value = "value";
    product.name = "name";

    myform.appendChild(product);
    myform.submit();
于 2014-12-09T18:24:36.110 回答
0

我创建了一个函数来执行此操作:

function PostDataRedirect(data, dataName, location) {
var form = document.createElement("form");

form.method = "POST";
form.action = location;

if (data.constructor === Array && dataName.constructor === Array) {
    for (var i = 0; i < data.length; i++) {
        var element = document.createElement("input");
        element.type = "hidden";
        element.value = data[i];
        element.name = dataName[i];
        form.appendChild(element);
    }
} else {
    var element1 = document.createElement("input");
    element1.type = "hidden";
    element1.value = data;
    element1.name = dataName;
    form.appendChild(element1);
}

document.body.appendChild(form);

form.submit(); 
}

提问的用法:

PostDataRedirect([ un, pw ], ["un", "pw"], "login.php");
于 2017-02-06T16:31:50.167 回答