我正在尝试创建一个表单并立即使用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();
}
答案 0 :(得分:64)
问题是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();
}
答案 1 :(得分:4)
修改后的代码: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();
}
答案 2 :(得分: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();
答案 3 :(得分: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");