0
我需要在選擇任何國家/地區後在frmState下拉框中預先填充狀態詳細信息。 但我是新來的ajax,我沒有足夠的知識。你能幫我做這個例程嗎?它在下面給出。 它可能值得很多。提前致謝。在PHP中使用ajax預填充相應國家/地區的詳細信息
我在MySQL的兩個表..
tbl_country
columns: country_id(auto inc id) | country_name | country_code
tbl_states
columns: state_id(auto inc id) | state_name | country_name
HTML代碼
<select class="txtselectcomp" name="frmCountry" id="frmCountry" onChange="showHint(this.value);" onblur="checkEmptyData('frmCountry');" required="required" >
<option value="">Select country</option>
<?php
for ($i = 0; $i < count($strCountries); $i++) { ?>
<option value="<?php
echo $strCountries[$i]['country_name']; ?>" <?php
if ($_POST['frmCountryName'] == $strCountries[$i]['country_name']) { ?> selected="selected" <?php
} ?>><?php
echo ucfirst($strCountries[$i]['country_name']); ?></option>
<?php
} ?>
</select>
<select class="txtselectcomp" name="frmState" id="frmState" onblur="checkEmptyData('frmState');" required="required" >
<option value="">Select State</option>
</select>
阿賈克斯腳本
<script language="javascript">
function showHint(str)
{
var xmlhttp;
if (str.length==0) {
document.getElementById("frmState").innerHTML="";
return;
}
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
}
else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status==200) {
document.getElementById("frmState").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","findState.php?value="+str,true);
xmlhttp.send(null);
}
</script>
功能
$strCountries = doSelectRecordsById('tbl_country', 'country_id, country_name', 'country_id', ' order by country_name ASC', '');
function doSelectRecordsById($strTableName, $strSelect='*', $strTableId, $strOrderBy = NULL, $strFieldValue = NULL)
{
if ($strFieldValue != NULL) {
$strWhereClause = " WHERE $strTableId = '".(int)$strFieldValue."'";
}
$strSqlRecords = "SELECT $strSelect FROM $strTableName $strOrderBy $strWhereClause";
$strSqlData = SelectQry($strSqlRecords);
if ($strWhereClause == '') {
return $strSqlData;
} else {
return $strSqlData[0];
}
}
function doSelectState($strIdent)
{
$strSelectsSql = "Select * from tbl_states Where country_name='".$strIdent."' ";
$strSelectsResult = SelectQry($strSelectsSql);
return $strSelectsResult[0];
}
findState.php
<?php
include ("config.php");
$country_name = $_GET["value"];
$sql = doSelectState($country_name);
?>
<select name="State" id="State">
<?php
for ($i = 0; $i < count($sql); $i++) {
$id = $sql[$i]['state_id'];
$state = $sql[$i]['state_name'];
echo '<option value="' . $id . '">' . $state . '</option>';
}
?>
</select>