Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
873 views
in Technique[技术] by (71.8m points)

creating and submitting a form with javascript

I'm trying to create a form and submit it immediately with javascript and I cannot figure out what I'm doing wrong. here is my code:

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();
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The problem is that createElement does not accept HTML. It accepts a tagname and returns a DOM element. You can then set the value attribute on this element to what you require.

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();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...