我看到很多人说在脚本中插入PHP语句是不可能的,但还有其他方法可以用来做吗?
我在网上找到了一个Jquery(?)脚本,允许我追加和删除文本框。 以下是代码的一部分:
<script>
$(`.buttons`).append (`<input type="text" name="txt"> <input type="button" class="btnRemove" value="Remove"><br>`); // end append
</script>
但是,我想通过从数据库填充来使用下拉列表<select>...</select>
,而不是使用文本框。话虽如此,我需要使用<?php (Retrieve stuffs from database and populate here) ?>
我尝试将php标记放在脚本标记中,但没有任何反应。我还能怎么做呢?
这是我的代码。哦,伙计,我真的不知道如何让我的代码在灰色框中。我已经在代码中声明了allFEArray。 (对不起我可怕的缩进,我还是新手)
<script>
$(document).ready (function () {
$('.btnAdd').click (function () {
$('.buttons').append (
<?php
$userCtrl = new user_controller();
$allFEArray = $userCtrl->retrieveAllFE();
if($allFEArray != null) { //if there are field engineers
echo 'Name: <select name="fieldEngineers[]" style="width: 180px;">';
foreach ($allFEArray as $fe) {
echo "<option value =".$fe.">".$fe."</option>";
}//end for each
echo '</select>';
echo ' <input type="button" class="btnRemove" value="Remove"><br>';
}
?>
); // end append
$('.btnRemove').on('click', function () {
$(this).prev().remove (); // remove the textbox
$(this).next ().remove (); // remove the <br>
$(this).remove (); // remove the button
});
}); // end click
}); // end ready
</script>
答案 0 :(得分:0)
除非您希望函数在单击时访问数据库,否则您需要执行以下操作:
<script>
$(document).ready (function () {
$('.btnAdd').click (function () {
$('.buttons').append (
<?php
$userCtrl = new user_controller();
$allFEArray = $userCtrl->retrieveAllFE();
if($allFEArray != null) { //if there are field engineers
echo '\'Name: <select name="fieldEngineers[]" style="width: 180px;">\'+';
foreach ($allFEArray as $fe) {
echo '\'<option value =".$fe.">".$fe."</option>"\'+';
}//end for each
echo "'</select>'+";
echo '\'<input type="button" class="btnRemove" value="Remove"><br>\'';
} ?>
); // end append
$('.btnRemove').on('click', function () {
$(this).prev().remove (); // remove the textbox
$(this).next ().remove (); // remove the <br>
$(this).remove (); // remove the button
});
}); // end click
}); // end ready
</script>