php & html inside Javascript


php & html inside Javascript

我想在JavaScript脚本中添加html标记和php代码

这是我的代码

<script>
function myFunction()
{
    var table = document.getElementById("myTable");
    var row = table.insertRow(2);
    var cell1 = row.insertCell(0);
    var cell2 = row.insertCell(1);
    var cell3 = row.insertCell(1);
    var cell4 = row.insertCell(1);
    cell1.innerHTML = "NEW CELL1";
    cell2.innerHTML = "NEW CELL2";
function myDeleteFunction()
{
    document.getElementById("myTable").deleteRow(2);
}
</script>

我想在cell1中添加select标记,并且我的select标记具有数据库中的选项值这是选择标签的代码::

<td>
    <select id="nlocation" name="nlocation" >
    <?php 
        $res = mysql_query("SELECT * FROM `nlocation` WHERE `nlocation` != '$location' ");
        if(mysql_num_rows($res)> 0)
        {
            for($i=0;$i<mysql_num_rows($res);$i++) {
                $row=mysql_fetch_assoc($res);       
                echo"<option value='$row[nlocation]'> $row[nlocation] </option>";       
            }
        }           
    ?>     
    </select>
</td>

简单!更换

echo"<option value='$row[nlocation]'> $row[nlocation] </option>";

通过

echo"<option value='" . $row['nlocation'] . "'>" . $row['nlocation'] . "</option>";

编辑:我还没有完全理解你的问题。。您必须记住值(在最后一次回波下):

$arr_data[] = $row;

并且,在您的javascript:中

cell1.innerHTML = "<?php echo $arr_data[0]['nlocation']; ?>";
cell2.innerHTML = "<?php echo $arr_data[1]['nlocation']; ?>";

有两种方法:

使用点添加字符串:"foo"$酒吧"foo";

echo"<option value='" . $row['nlocation'] . "'> " . $row['nlocation'] . " </option>";

或者(我更喜欢),使用backets foo{$bar}foo

echo"<option value='{$row['nlocation']}'> {$row['nlocation']} </option>";

注意:我更喜欢第二个选项,因为我们使用"。所以PHP无论如何都会在字符串中查找变量。如果你想要更快的脚本,请确保对每个文本使用'fo'

最好将PHP脚本创建的HTML内容分配给JavaScript变量

<script type="text/javascript">
    var selectContent = "<select id='"nlocation'" name='"nlocation'">" +
        "<?php 
            $res=mysql_query("SELECT * FROM `nlocation` WHERE `nlocation` != '$location' ");
            if(mysql_num_rows($res)> 0)
            {
                for($i=0;$i<mysql_num_rows($res);$i++) {
                    $row=mysql_fetch_assoc($res);
                    echo "<option value='".$row['nlocation']."'> ".$row['nlocation']." </option>";
                }
            }
        ?>" +
        "</select>";
</script>

然后只需将innerHTMLselectContent变量HTML放入您的单元格中。

编辑:我会再次尝试回答你的问题。

不能用表单元素替换单元格。我之前的回答将动态生成的select元素和选项分配给JavaScript变量。从这里,您可以将选择代码插入到您的表格单元格中,如下所示:

<script>
function myFunction()
{
    var table = document.getElementById("myTable");
    var row = table.insertRow(2);
    var cell1 = row.insertCell(0);
    var cell2 = row.insertCell(1);
    var cell3 = row.insertCell(1);
    var cell4 = row.insertCell(1);
    cell1.innerHTML = "NEW CELL1";
    // INSERTING SELECT CODE HERE!!
    cell2.innerHTML = selectContent;
function myDeleteFunction()
{
    document.getElementById("myTable").deleteRow(2);
}
</script>