为什么php中的php代码无法改变innerHTML的值?

时间:2014-05-17 06:40:48

标签: javascript php html innerhtml

此页面包含两个网页,insert6.php正在使用iframe。
enter image description here

该网页的完整代码。
form6.php

<!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=big5" />
<title>CCC</title>
<style>
#tlist tr:last-child td {
    background-color:#CCCCCC;
}
table{
    table-layout: fixed;
}
th, td {
    overflow: hidden;
}
#container
{ 
margin-left:auto; 
margin-right:auto; 
width:600px;
}
</style>
</head>
<body>
<h3>New Record</h3>
<script language="JavaScript" type="text/javascript">
function addRowToTable()
{
 var tbl = document.getElementById('tblSample');
 var lastRow = tbl.rows.length;
 // if there's no header row in the table, then iteration = lastRow + 1
 var iteration = lastRow;
 var row = tbl.insertRow(lastRow);

 // left cell
 var cellLeft = row.insertCell(0);
 var che = document.createElement('input');
 che.type = 'checkbox';
 che.id = 'op'+ iteration;
 che.name= 'checkbox';
 cellLeft.appendChild(che); 

 // right cell
 var cellRight = row.insertCell(1);
 var el = document.createElement('input');
 el.type = 'text';
 el.name = 'txtRow[]';
 el.id = 'txtRow' + iteration;
 el.size = 40;

 el.onkeypress = keyPressTest;
 cellRight.appendChild(el);

 // select cell
 var cellRightSel = row.insertCell(2);
 var sel = document.createElement('select');
 //sel.type = 'text';
 sel.name = 'selRow[]';
 sel.id = 'selRow' + iteration;
 sel.options[0]= new Option("<?php
    mysql_connect("localhost", "root", "root") or
    die("Could not connect: " . mysql_error());
    mysql_select_db("partition");
    $query = "SELECT tile FROM material ORDER BY  `material`.`Material_ID` ASC ;";
    $result = mysql_query($query);
    $row = mysql_fetch_row($result);
    mysql_data_seek($result,0);
    while ($row=mysql_fetch_row($result))
        {
    for ($i=0;$i<mysql_num_fields($result);$i++)
        {
    if ($row[$i]=="FF")
    echo($row[$i]);
        }
        }   
    mysql_free_result($result); 
  ?>");
  sel.options[1]= new Option("<?php
    mysql_connect("localhost", "root", "root") or
    die("Could not connect: " . mysql_error());
    mysql_select_db("partition");
    $query = "SELECT tile FROM material ORDER BY  `material`.`Material_ID` ASC ;";
    $result = mysql_query($query);
    $row = mysql_fetch_row($result);
    mysql_data_seek($result,0);
    while ($row=mysql_fetch_row($result))
        {
    for ($i=0;$i<mysql_num_fields($result);$i++)
        {
    if ($row[$i]=="DD")
    echo($row[$i]);
        }
        }   
    mysql_free_result($result); 
  ?>");
  sel.options[2]= new Option("<?php
    mysql_connect("localhost", "root", "root") or
    die("Could not connect: " . mysql_error());
    mysql_select_db("partition");
    $query = "SELECT tile FROM material ORDER BY  `material`.`Material_ID` ASC ;";
    $result = mysql_query($query);
    $row = mysql_fetch_row($result);
    mysql_data_seek($result,0);
    while ($row=mysql_fetch_row($result))
        {
    for ($i=0;$i<mysql_num_fields($result);$i++)
        {
    if ($row[$i]=="TT")
    echo($row[$i]);
        }
        }   
    mysql_free_result($result); 
  ?>");
  sel.options[3]= new Option("<?php
    mysql_connect("localhost", "root", "root") or
    die("Could not connect: " . mysql_error());
    mysql_select_db("partition");
    $query = "SELECT tile FROM material ORDER BY  `material`.`Material_ID` ASC ;";
    $result = mysql_query($query);
    $row = mysql_fetch_row($result);
    mysql_data_seek($result,0);
    while ($row=mysql_fetch_row($result))
        {
    for ($i=0;$i<mysql_num_fields($result);$i++)
        {
    if ($row[$i]=="GG")
    echo($row[$i]);
        }
        }   
    mysql_free_result($result); 
  ?>");
  sel.options[4]= new Option("<?php
    mysql_connect("localhost", "root", "root") or
    die("Could not connect: " . mysql_error());
    mysql_select_db("partition");
    $query = "SELECT tile FROM material ORDER BY  `material`.`Material_ID` ASC ;";
    $result = mysql_query($query);
    $row = mysql_fetch_row($result);
    mysql_data_seek($result,0);
    while ($row=mysql_fetch_row($result))
        {
    for ($i=0;$i<mysql_num_fields($result);$i++)
        {
    if ($row[$i]=="RR")
    echo($row[$i]);
        }
        }   
    mysql_free_result($result); 
  ?>");
  sel.options[5]= new Option("<?php
    mysql_connect("localhost", "root", "root") or
    die("Could not connect: " . mysql_error());
    mysql_select_db("partition");
    $query = "SELECT tile FROM material ORDER BY  `material`.`Material_ID` ASC ;";
    $result = mysql_query($query);
    $row = mysql_fetch_row($result);
    mysql_data_seek($result,0);
    while ($row=mysql_fetch_row($result))
        {
    for ($i=0;$i<mysql_num_fields($result);$i++)
        {
    if ($row[$i]=="AA")
    echo($row[$i]);
        }
        }   
    mysql_free_result($result); 
  ?>");

 cellRightSel.appendChild(sel);
}
function keyPressTest(e, obj)
{
 var validateChkb = document.getElementById('chkValidateOnKeyPress');
 if (validateChkb.checked) {
   var displayObj = document.getElementById('spanOutput');
   var key;
   if(window.event) {
     key = window.event.keyCode;
   }
   else if(e.which) {
     key = e.which;
   }
   var objId;
   if (obj != null) {
     objId = obj.id;
   } else {
     objId = this.id;
   }
   displayObj.innerHTML = objId + ' : ' + String.fromCharCode(key);
 }
} 
function openInNewWindow(frm)
{
 // open a blank window
 var aWindow = window.open('', 'TableAddRowNewWindow',
  'scrollbars=yes,menubar=yes,resizable=yes,toolbar=no,width=400,height=400');

 // set the target to the blank window
 frm.target = 'TableAddRowNewWindow';

 // submit
 frm.submit();
}
function validateRow(frm)
{
 var chkb = document.getElementById('chkValidate');
 if (chkb.checked) {
   var tbl = document.getElementById('tblSample');
   var lastRow = tbl.rows.length - 1;
   var i;
   for (i=1; i<=lastRow; i++) {
     var aRow = document.getElementById('txtRow' + i);
     if (aRow.value.length <= 0) {
       alert('Row ' + i + ' is empty');
       return;
     }
   }
 }
 openInNewWindow(frm);
}
function deleteAll(obj){ 
var checked = document.getElementsByName(obj); 
debugger 
for(var i = 0; i < checked.length; i ++){ 
if(checked[i].checked){ 
var tr=checked[i].parentNode.parentNode; 
var tbody=tr.parentNode; 
tbody.removeChild(tr); 
i--; 
} 
} 
}
</script>
<!--Input Data-->
<form action="insert6.php" method="post" target="myframe">
Series:
<?php
    function series(){
    mysql_connect("localhost", "root", "root") or
    die("Could not connect: " . mysql_error());
    mysql_select_db("partition");

    $query = "SELECT Series_NAME FROM series;";
    $result = mysql_query($query);
    $row = mysql_fetch_row($result);
    mysql_data_seek($result,0);
    while ($row=mysql_fetch_row($result))
        {
    for ($i=0;$i<mysql_num_fields($result);$i++)
        {
    echo("<option>".$row[$i]."</option>");
        }
        }
    mysql_free_result($result);
    }
?>
<select name="choose series">
<?php series(); ?>
</select><br>
<?php
    function height(){
    mysql_connect("localhost", "root", "root") or
    die("Could not connect: " . mysql_error());
    mysql_select_db("partition");

    $query = "SELECT height FROM width_height GROUP BY height;";
    $result = mysql_query($query);
    $row = mysql_fetch_row($result);
    mysql_data_seek($result,0);
    while ($row=mysql_fetch_row($result))
        {
    for ($i=0;$i<mysql_num_fields($result);$i++)
        {
    echo("<option>".$row[$i]."</option>");
        }
        }
    mysql_free_result($result);
    }
?>
<p>Height(MM):
<select name="height" id="height0">
<?php height(); ?>
</select></p>
<?php
    function width(){
    mysql_connect("localhost", "root", "root") or
    die("Could not connect: " . mysql_error());
    mysql_select_db("partition");

    $query = "SELECT width FROM width_height GROUP BY width;";
    $result = mysql_query($query);
    $row = mysql_fetch_row($result);
    mysql_data_seek($result,0);
    while ($row=mysql_fetch_row($result))
        {
    for ($i=0;$i<mysql_num_fields($result);$i++)
        {
    echo("<option>".$row[$i]."</option>");
        }
        }
    mysql_free_result($result);
    }
?>
<p>Width (MM):
<select name="width" id="width0">
<option><?php width(); ?></option>
</select><br>

<table border="1" id="tblSample">
 <tr>
   <td><input type="checkbox" id="op0" name="checkbox">
   </td>
   <td><input type="text" name="txtRow[]"
    id="txtRow0" size="40"/></td>
   <td>
   <select name="selRow[]" id="selRow0">
   <?php
    mysql_connect("localhost", "root", "root") or
    die("Could not connect: " . mysql_error());
    mysql_select_db("partition");

    $query = "SELECT tile FROM material ORDER BY `material`.`Material_ID` ASC ;";
    $result = mysql_query($query);
    $row = mysql_fetch_row($result);
    mysql_data_seek($result,0);
    while ($row=mysql_fetch_row($result))
        {
    for ($i=0;$i<mysql_num_fields($result);$i++)
        {
    echo("<option>".$row[$i]."</option>");
        }
        }
    mysql_free_result($result);
    ?>
   </select>
   </td>
 </tr>
</table>
<input type="button" value="Add" onClick="addRowToTable();" />
<input type="button" name="delete_button" value="Delete" onClick="deleteAll('checkbox');" />
<input type="submit" name="submit" value="Submit" onclick="test();"/>
</form>
<script src="https://dl.dropboxusercontent.com/u/19096175/blog/selectDate/selectDate.js" type="text/javascript"></script>
Choose Date:<input onfocus="HS_setDate(this)" readonly="" type="text" value="Check" />
<br />
<hr/>
<iframe src="insert6.php" name="myframe" id="myframe" width="650" height="400" scrolling="no" frameborder="0"> 
</iframe> 
</body>
</html>

该网页的完整代码。
insert6.php

<!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>
<title>DDD</title>
<style>
#tlist tr:last-child td {
    background-color:#CCCCCC;
}
table{
    table-layout: fixed;
}
th, td {
    overflow: hidden;
}
#container
{ 
margin-left:auto; 
margin-right:auto; 
width:600px;
}
</style>
</head>
<body>

<?php
/*
$name = $_POST['selRow'];
$qty = $_POST['txtRow'];

foreach( $qty as $v ) {
print $v."<br>";
}

foreach( $name as $v ) {
print $v."<br>";
}
*/
?>
<script>
function delrecord(obj)  
{  
  obj.parentNode.parentNode.parentNode.removeChild(obj.parentNode.parentNode);  
  var delbutton=document.getElementsByName("del");  
  var newzum=0;  
  for(var j=1;j <document.getElementsByName("del").length+1;j++)  
  {  
  newzum+=parseFloat(document.getElementById('total'+j).innerHTML);    
  }  
  znum.innerHTML =newzum; 
}  
function caltotal(e){
var fqty=document.getElementById('qty' +iteration);  
var fprice=document.getElementById('price' + iteration);  
var ftotal=document.getElementById('total'+ iteration);
var delbutton=document.getElementsByName("del");  
ftotal.innerHTML= fqty.innerHTML * fprice.innerHTML;

newzum =0;
for(var j=1;j <=document.getElementsByName("del").length;j++)  
{  
newzum += parseFloat(document.getElementById('total'+j).innerHTML);
}
znum.innerHTML = newzum;
}
</script>

<div class="container">
<table width="450" border="0" cellspacing="1" cellpadding="0" class="tb" id="tlist">  
    <tr class="tit2">
    <td>QTY </td>
    <td>TILE </td>
    <td>HEIGHT </td>
    <td>WIDTH </td>
    <td>PRICE </td>
    <td>TOTAL </td>
    <td>Action </td>  
    </tr> 
    <tr class="tit3"> 
<?php
if(isset($_POST["submit"])){ 
$t=count($_POST['selRow']); 
$w=count($_POST['txtRow']);
for($i=0;$i<$t;$i++)
{
$qty[$i]= $_POST['txtRow'][$i];
$tile[$i]= $_POST['selRow'][$i];
$height = $_POST['height'];
$width = $_POST['width'];

echo "<tr class='tit3'><td>";
echo "".$qty[$i]."<br>";
echo "</td>";
echo "<td>";
echo "".$tile[$i]."<br>";
echo "</td>";
echo "<td>";
echo "".$height."<br>";
echo "</td>";
echo "<td>";
echo "".$width."<br>";
echo "</td>";
echo "<td>";
    mysql_connect("localhost", "root", "root") or
    die("Could not connect: " . mysql_error());
    mysql_select_db("partition");
    //foreach($_POST['selRow'] as $tile){

    $query = "SELECT `Price` FROM `actualpanelmaterialsize` WHERE `Material ID` IN (SELECT `Material_ID` FROM `material` WHERE `Tile` = '".$tile[$i]."') AND  `Width_Height ID` IN (SELECT `Width_Height ID` FROM `width_height` WHERE `Width` =".$_POST['width']." AND `Height` =".$_POST['height'].");";
    $result = mysql_query($query);
    $row = mysql_fetch_row($result);
    mysql_data_seek($result,0);
    while ($row=mysql_fetch_row($result))
        {
    $price = $row[0];
    echo $price."<br>";
        }
    //}
echo "</td>";
echo "<td id='total[$i]'>";
echo $total[$i]=$price*$qty[$i];
echo "</td>";
echo "<td>";
echo "<input type='button' value='Delete' name='del' onclick='delrecord(this);'>";
echo "</td>";
echo "</tr>";
}
echo "<script>";
echo "newzum =0;";
echo "for(var j=0;j <=document.getElementsByName('del').length+1;j++) {" ;
echo "for (var i=0;i<=document.getElementById('total['+i+']').innerHTML.length;i++){";
echo "newzum += parseFloat(document.getElementById('total['+i+']').innerHTML);";
echo "}";
echo "}";
echo "document.getElementById('znum').innerHTML = newzum;";
echo "</script>";
} 
?> 

</tr> 
<tr class="tit3"> <td>Total </td> <td colspan=3> </td> <td colspan=2 align='right'> <b id="znum">0</b> </td> <td colspan=1> </td> </tr>
</table>
<script>
/*
for (var i=0;i<=document.getElementById("total["+i+"]").innerHTML.length;i++){
window.alert(document.getElementById("total["+i+"]").innerHTML);
}
*/
function Check(){
for (var i=0;i<=document.getElementById("total["+i+"]").innerHTML.length;i++){
window.alert(newzum);
}
}
</script>
<input type="button" value="Check" onClick="Check();"/>
</div>
</body>
</html>

最后,我问你们为什么znum.innerHTML无法改变这个值。 现在,我将javascript代码放在php语言中,结果仍然错误......

我的预期结果:
enter image description here

现在我看到了结果:
enter image description here

点击“检查”按钮后看到newznum是否正确,但znum.innerHTML无法更改此值 enter image description here


将表单传递给insert6.php时,总计应该更改该值。 现在,我不能这样做。 有人在这看到问题吗?
请你帮助我,我知道我哪里弄错了。

感谢您阅读我的问题!
我希望我会收到帮助我解决问题的答案

3 个答案:

答案 0 :(得分:2)

首先,逻辑分离非常重要,而我所看到的代码就是你从视图本身进行数据库调用。这显示了糟糕的编码方式。这将使您难以管理您的代码。

sel.options[0]= new Option("<?php
    mysql_connect("localhost", "root", "root") or
    die("Could not connect: " . mysql_error());
    mysql_select_db("partition");
    $query = "SELECT tile FROM material ORDER BY  `material`.`Material_ID` ASC ;";
    $result = mysql_query($query);
    $row = mysql_fetch_row($result);
    mysql_data_seek($result,0);
    while ($row=mysql_fetch_row($result))
        {
    for ($i=0;$i<mysql_num_fields($result);$i++)
        {
    if ($row[$i]=="FF")
    echo($row[$i]);
        }
        }   
    mysql_free_result($result); 
  ?>");

现在回答你的问题:

echo "newzum =0;";
echo "for(var j=0;j <=document.getElementsByName('del').length+1;j++) {" ;
echo "for (var i=0;i<=document.getElementById('total['+i+']').innerHTML.length;i++){";
echo "newzum += parseFloat(document.getElementById('total['+i+']').innerHTML);";
echo "}";
echo "}";
echo "document.getElementById('znum').innerHTML = newzum;";
echo "</script>";

这些代码行将在页面加载为php之前执行。

因此,当呈现页面时,脚本将找不到document.getElementsByName('del'),因此它将抛出未定义的错误。

要克服这一点,请在onload函数中执行这些操作。

window.onload = function() {
 // Inside this method put those lines. It will work.
}

答案 1 :(得分:0)

您的代码太长了,但我会尝试从您的标题中回答。

你必须了解php和javascript是如何工作的。 php是一种服务器端语言,而javascript是一种客户端语言。你不能在javascript中执行php。 php在服务器上进行处理,然后将结果返回给客户端。在此之后,服务器不知道客户端状态。

为了更改innerHTML的值,您只需使用javascript即可。如果你需要以某种方式与php交互,你应该将AJAX调用发送到服务器,php脚本可以处理并返回新数据。

答案 2 :(得分:0)

PHP只会回显Javascript代码,这很好,但不必要复杂。您只需在页面中输入Javascript代码即可。

现在的实际问题是这一行:

 document.getElementById('znum').innerHTML = newzum;

它是全局范围内的一行Javascript,一旦浏览器在加载页面期间遇到它,它就会被执行。 但元素应该修改('znum')是页面上的几行:

<b id="znum">0</b> 

这基本上意味着当脚本执行时元素还没有准备好,因此无法找到它。

解决方案相对简单:稍后(在底部)执行Javascript,因此它将在已加载所有相关元素时执行。

此类脚本错误会导致错误或警告在浏览器的开发人员工具(F12)的“控制台”选项卡中显示。因此,请确保在调试Javascript时始终注意这一点。这是一个你应该作为Web开发人员掌握的工具。 :)