在IE / Mozilla中动态添加javascript中的表单元素

时间:2014-05-06 06:59:52

标签: javascript html

所以,我尝试过很多东西,但没有用这个

建立一个解决方法

我有这个代码在Chrome上运行正常。但它确实不适用于Mozilla或IE,在控制台中它不会显示任何错误。它只是没有用。

<?php

echo"<script>alert('okay');</script>";

?>


<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
    <meta charset="UTF-8" />
</head>
    <script type="text/javascript" LANGUAGE="JavaScript1.3">
        function name3() {
            var abc = document.createElement("FORM");
                //abc.setAttribute("method","POST");
            abc.method = "POST";
            abc.action = "http://localhost/2.php";
            var a = document.createElement("INPUT");
                /*a.setAttribute("type","text");
                a.setAttribute("name","a");
                a.setAttribute("value","abc");*/
            a.name = 'a';
            a.value = "abc";
            abc.appendChild(a);
            abc.submit();
        }
    </script>
    <input type = "button" onclick = "name3();" value = "click">
</html> 

而不是a.name,我也尝试过使用a.setAttribute但仍然没有工作

请帮忙!!!谢谢:))

2 个答案:

答案 0 :(得分:0)

您应该将表格附加到正文,然后在发布后将其删除。目前您没有将表单添加到DOM。它实际上需要在DOM中以页面加载的方式发送。

完整代码

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">

<head>
    <meta charset="UTF-8" />
    <script type="text/javascript">
        function name3() {
            var form = document.createElement("FORM");
            form.method = "POST";
            form.action = "http://localhost/2.php";
            var a = document.createElement("INPUT");
            a.name = 'a';
            a.value = "abc";
            form.appendChild(a);

            //Apend form to body
            document.getElementsByTagName('body')[0].appendChild(form);

            //Submit form
            form.submit();

            // But once the form is sent, it's useless to keep it.
            document.getElementsByTagName('body')[0].removeChild(form);
        }
    </script>
</head>

<body>
    <input type="button" onclick="name3();" value="click" />
</body>

</html>

答案 1 :(得分:0)

您应首先将新元素添加到DOM树,然后提交表单。如果您不想显示它们,可以添加样式来隐藏元素。

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
    <meta charset="UTF-8" />
</head>
<script type="text/javascript">
    function name3() {
        var abc = document.createElement("FORM");
            //abc.setAttribute("method","POST");
        abc.method = "POST";
        abc.action = "http://localhost/2.php";
        var a = document.createElement("INPUT");
            /*a.setAttribute("type","text");
            a.setAttribute("name","a");
            a.setAttribute("value","abc");*/
        a.name = 'a';
        a.value = "abc";
        abc.appendChild(a);

        document.getElementById("body").appendChild(abc);
        abc.submit();
    }
</script>
<body id="body">
    <input type = "button" onclick = "name3();" value = "click">
</body>