php获取通过javascript动态创建checkbox的值的一个小小的问题
以下两段程序只有一个小小的差别,但是生成的值却大相径庭
1. test.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
</head>
<body>
<form action="test.php" method="post">
<div>
<input type="text" name="name" />
<input type="button" onclick="addname();" value="add"/>
<span id="showname"></span>
</div>
<input type="submit" value="提交" />
</form>
</body>
<script type="text/javascript">
function addname(){
var the_name = document.getElementsByName('name')[0];
var _input = document.createElement('input');
var _name = document.createTextNode(the_name.value);
var _showname = document.getElementById("showname");
_input.type = "checkbox";
_input.value = the_name.value;
_input.name = "myname[]";
_showname.appendChild(_input);
_showname.appendChild(_name);
_input.checked = "checked";
the_name.value = "";
}
</script>
</html>
2.test.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
</head>
<body>
<form action="test.php" method="post">
<div>
<input type="text" name="name" />
<input type="button" onclick="addname();" value="add"/>
<span id="showname"></span>
</div>
<input type="submit" value="提交" />
</form>
</body>
<script type="text/javascript">
function addname(){
var the_name = document.getElementsByName('name')[0];
var _input = document.createElement('input');
var _name = document.createTextNode(the_name.value);
var _showname = document.getElementById("showname");
_input.value = the_name.value;
_input.name = "myname[]";
_input.type = "checkbox";
_showname.appendChild(_input);
_showname.appendChild(_name);
_input.checked = "checked";
the_name.value = "";
}
</script>
</html>
3.test.php
<?php
$myname = "";
if($_POST['myname']){
$myname = $_POST['myname'];
}else{
echo "传入数据为空";
}
foreach($myname as $value){
echo $value.",";
}
?>
两段test.html的程序只有一个小小的差别,就是创建checkbox标签的时候,_input.type = "checkbox"的位置不同。但是在IE下第一个test.html传输到后台的数据是正确的,第二个test.html传输到后台的值始终是"on"。而如果在FireFox下,两个程序都能正常运行。这两段程序是从一个项目里面摘下来的,运行的时候结果始终不对。昨天花了一整天都没有找到这个错误,我一直以为是javascript在IE和FireFox下的兼容性问题,直到后来我重新写一段小程序,发现IE下也能正常运行,才通过对比把这个错误揪出来。
为什么会出现这个错误,由于我javascript也是初学,想不出一个合理的解释,百度一下好像也没有人碰到过同样的错误。所以发上来,跟大家共同探讨一下。希望有了解的朋友来指导指导。
浙公网安备 33010602011771号