我的index.php文件正确加载了所有国家/地区,如下图所示:
这也是我在第一次加载中看到的:
<div class="content">
<?php
include("config.php");
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select name="country" id="country">
<option value="">Select Country</option>
<?php
$db = pg_connect("$db_host $db_name $db_username $db_password");
$query = "SELECT country FROM countries";
$result = pg_query($query);
if (!$result) {
echo "Problem with query " . $query . "<br/>";
echo pg_last_error();
exit();
}
while($myrow = pg_fetch_assoc($result)) {
printf ("<option value=$myrow[country_id]>$myrow[country]</option>");
}
?>
</select>
<br>
<select name="state" id="state">
<option value="">Select State</option>
</select>
<br>
<select name="city" id="city">
<option value="">Select City</option>
</select>
<script type="text/javascript">
$(document).ready(function(){
$('#country').on('change',function(){
var countryID = $(this).val();
if(countryID){
$.ajax({
type:'POST',
url:'ajaxData.php',
data:'country_id='+countryID,
success:function(html){
$('#state').html(html);
$('#city').html('<option value="">Select state first</option>');
}
});
}else{
$('#state').html('<option value="">Select country first</option>');
$('#city').html('<option value="">Select state first</option>');
}
});
$('#state').on('change',function(){
var stateID = $(this).val();
if(stateID){
$.ajax({
type:'POST',
url:'ajaxData.php',
data:'state_id='+stateID,
success:function(html){
$('#city').html(html);
}
});
}else{
$('#city').html('<option value="">Select state first</option>');
}
});
});
</script>
然后我有ajaxData.php文件如下:
<?php
//Include database configuration file
include("config.php");
if(isset($_POST["country_id"]) && !empty($_POST["country_id"])){
//Get all state data
$query = "SELECT state FROM states WHERE country = ".$_POST['country_id'];
$result = pg_query($query);
if (!$result) {
echo "Problem with query " . $query . "<br/>";
echo pg_last_error();
exit();
}
//Count total number of rows
$get_total_rows = pg_numrows($results);
//Display states list
if($get_total_rows > 0){
echo '<option value="">Select state</option>';
while($myrow = pg_fetch_assoc($result)) {
echo '<option value="'.$myrow['state_id'].'">'.$myrow['state'].'</option>';
}
}else{
echo '<option value="">State not available</option>';
}
}
选择国家/地区后,我会看到以下内容:
由于选择器中的文本已从&#34;选择状态&#34;到&#34;首先选择国家/地区&#34;,当$(&#39;#country&#39;)on(&#39;更改&#39;,function()进入时,它会在我的javascript功能中找到它
else{
$('#state').html('<option value="">Select country first</option>');
$('#city').html('<option value="">Select state first</option>');
而不是通过:
if(countryID){
$.ajax({
type:'POST',
url:'ajaxData.php',
data:'country_id='+countryID,
success:function(html){
$('#state').html(html);
$('#city').html('<option value="">Select state first</option>');
}
});
显然有些东西不起作用,但我无法看清楚它是什么。
任何帮助将不胜感激。