2014-05-06 104 views
-2

所以,我已经试过一堆东西,但没有建立一种解决方法与此在JavaScript动态添加表单元素在IE/Mozilla的

我有这样的代码能正常工作在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尝试,但仍然没有工作

请帮助!谢谢:)

+0

你没有标签。它可能会导致问题(因为DOM无效) – Gwenc37

回答

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> 
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>