【发布时间】:2019-08-15 23:42:31
【问题描述】:
我正在尝试设置一个选择框,该框将根据先前选择的州显示城市。
基本上,我使用 ajax 运行我的 php.file 来填充我的<option>。在php文件中我成功通过了预选状态查询数据库。但是,现在,为了填充<option>,我使用ajax 成功调用php 文件,但是,每当我尝试传递包含php 代码的变量时,它就会显示为!-- 和-- 的注释。
// hmtl
<select id="select-city" required >
<option disabled selected>Selecione sua Cidade</option>
</select>
// js code
function fillSelectCity () {
var getState = document.getElementById('selectState');
var stateID = getState.options[getState.selectedIndex].value;
$.ajax ({
type: "POST",
url: "fillcity.php",
data: { stateID : stateID },
success: function (){
var phpfile = "'fillcity.php'"
var tag = "<?php include_once " + phpfile + " ?>";
$('#select-city').html(tag);
/// here the output is "<!-- ?php include_once 'fillcity.php' ? -->"
}
})
}
//php file
<?php
$conn = mysqli_connect("host", "user", "pass", "db");
if(isset($_POST['stateID']))
{
$stateID = $_POST['stateID'];
}
$query = "SELECT * FROM states WHERE stateID = '$stateID'";
$result_one = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result_one); //my table has a specific ID for each state, so I am fetching the acronoym of the state according to the id;
$stateUf = $row['uf']; // passing the acronym to the $stateUf
mysqli_free_result($result_one);
$queryCity = "SELECT * FROM city WHERE Uf = '$stateUf'"; //query all cities with the acronym
if ($result = mysqli_query($conn, $queryCity)){
while ($row = mysqli_fetch_assoc($result)){
$id = $row['cityID'];
$name = $row['cityName'];
$name = utf8_encode($name);
echo <<< EOT
"<option value="$id">$name</option>"
EOT;
}
mysqli_free_result($result);}
else {echo "<option>Error</option>";}
?>
我希望通过循环遍历 php 文件中的表 city 来填充我的选择选项。标签<?php include_once 'fillcity.php' ?> 用于填充状态选择。可能有一种更直接的方式来进行相应的填充,但由于我是编程新手,我正试图自己解决问题。但是,请随意推荐其他方法,因为我不确定我打算做的事情是否会奏效。谢谢!
【问题讨论】:
-
您不能在 PHP 代码中使用 JavaScript 变量。 PHP 脚本完成后,JavaScript 在客户端上运行。
-
如果
fillSelectCity函数不在.php文件中,<?php将不会被PHP执行,它会被当作JavaScript字面量对待。 -
这就是您收到评论的原因,您将
<?php放入您的 HTML 中,它不是有效的 HTML 标记。
标签: javascript php mysql ajax select