使用HTML表单生成字符串?

时间:2015-10-22 03:21:11

标签: javascript html api

我正在尝试创建一个页面,该页面将使用用户名,密码和电子邮件在我的SubSonic页面上创建用户。我有这个:

<!DOCTYPE html>
<html>
<head>
<script>
    function myFunction() {
    var form = document.getElementById("myForm");
    var server = "http://*****.*****.org:4040/rest/createUser.view?";
    var params = "&commentRole=true&u=*****&p=*****&v=1.12.0&c=myapp"; 
    var tosend = server.concat(form,params);
    document.write(tosend);
    }
</script>
</head>
<body>

<form id="myForm">
   Username: <input type="text" name="username"><br>
   Password: <input type="password" name="password"><br>
   Email: <input type="email" name="email"><br><br>
   <input type="button" value="Submit" onclick=myFunction()>
</form>

</body>
</html>

但是当我在字段中输入文本时,我得到一个这样的输出:

http://*****.*****.org:4040/rest/createUser.view?[object HTMLFormElement]&commentRole=true&u=*****&p=*****&v=1.12.0&c=myapp

我一直在寻找,试图弄清楚如何将[object HTMLFormElement]生成为字符串。有没有人对我做错了什么有任何想法?

1 个答案:

答案 0 :(得分:0)

你可以在脚本标签中尝试这样简单的事情:

<!DOCTYPE html>
<html>
<head>
<script>
    function myFunction() {
        var server = "http://*****.*****.org:4040/rest/createUser.view?";
        var params = "&commentRole=true&u=*****&p=*****&v=1.12.0&c=myapp"; 

        var name = document.getElementsByName("name").value;    
        var password = document.getElementsByName("password").value;
        var email = document.getElementsByName("email").value;

        /*
            to access tag values by name
            name=document.getElementsByName("name")[0].value;
            password=document.getElementsByName("password")[0].value;
            email=document.getElementsByName("email")[0].value;

            looping this will do
        */  

        var tosend = server + "" + "name=" + name + "&password=" + password + "&email=" + email + "" + params;
        document.write(tosend);
    }
</script>
</head>
<body>

<form id="myForm">
   Username: <input type="text" name="username" id="name"><br>
   Password: <input type="password" name="password" id="password"><br>
   Email: <input type="email" name="email" id="email"><br><br>
   <input type="button" value="Submit" onclick=myFunction()>
</form>

</body>
</html>

实际上,获取表单值的任何动态方法都可以,例如循环表单值并将其存储在变量上。