我正在尝试设置一个选择框,该框将根据州的先前选择显示城市。
基本上,我使用 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>";}
?>
我希望通过循环遍历cityphp 文件中的表来填充我的选择选项。该标签<?php include_once 'fillcity.php' ?>用于填充状态选择。也许,可能有一种更直接的方法来相应地填充,但由于我是编程新手,我正在尝试自己解决问题。但是,请随意推荐其他方法,因为我不确定我打算做的事情是否会奏效。谢谢!
心有法竹
三国纷争