2014-09-03 90 views
0

我需要使用ajax級聯兩個下拉框。在我的例行公事中,第一次下降是針對國家,第二次是針對國家。當我選擇國家時,州下拉菜單顯示這個國家的狀態。請在代碼中幫助我。提前致謝。
使用ajax級聯兩個下拉框

我的Ajax功能:

<script type="text/javascript"> 
function showstate(str) 
{ 
if (str=="") 
{ 
document.getElementById("fieldstate").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("fieldstate").innerHTML=xmlhttp.responseText; 
} 
} 
xmlhttp.open("GET","state_ajax.php?q="+str,true); 
xmlhttp.send(); 
} 
</script> 

我的HTML代碼:

 <select name="frmCountry" id="frmCountry" class="fiels" onchange="showstate(this.value)" onblur="checkEmpty('frmCountry', 'error_country', 'Please select the country');"> 
     <option value="">Please Select</option> 
     <?php for($i=0;$i<count($strCountries);$i++) { ?> 
      <option value="<?php echo $strCountries[$i]['coun_name']; ?>" <?php if($_POST['frmCountry']==$strCountries[$i]['coun_name']) { ?> selected="selected" <?php } ?>><?php echo ucfirst($strCountries[$i]['coun_name']); ?></option> 
     <?php } ?> 
     </select> 

     <select name="frmState" id="frmState" class="fiels" onblur="checkEmpty('frmState', 'error_state', 'Please select the state');"> 
     <option value="">Please Select</option> 
     </select> 

state_ajax.php:

<?php 
$q=$_GET["q"]; 

include("includes/config.php"); 

$strStates = doSelectCountryById('state_name', $q); 

echo "<select>" 
for($i=0;$i<count($strStates);$i++) { 
echo "<option>" . $strStates[$i]['state_name'] . "</option>"; 
} 
echo "</select>"; 
?> 

上面的代碼是用於級聯使用AJAX的兩個下拉框,但第二個下拉菜單無法顯示,請幫助我在代碼中。在此先感謝...

+0

http://stackoverflow.com/help/mcve 請deiscribe會發生什麼,應該怎樣,產生什麼錯誤,這行是有問題的,等等。「第二無法顯示」是不夠的。不要忘記格式化和縮進你的代碼,使其可讀。 – NDM 2014-09-03 07:37:12

回答

1

下拉列表中PHP 創建index.php文件並粘貼以下代碼:

<?php 
$con = mysql_connect('localhost', 'root', ''); 
if (!$con) { 
    die('Could not connect: ' . mysql_error()); 
} 
mysql_select_db('prem'); 
$query="SELECT * FROM country"; 
$result=mysql_query($query); 
?> 

<html> 
<head> 
<title>Country State City Dropdown Using Ajax</title> 
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> 
<script language="javascript" type="text/javascript"> 
function getXMLHTTP() { //function to return the xml http object 
var xmlhttp=false;   
try{ 
xmlhttp=new XMLHttpRequest(); 
} 
catch(e){        
                try{           
xmlhttp= new ActiveXObject("Microsoft.XMLHTTP"); 
} 
catch(e){ 
try{ 
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); 
} 
catch(e1){ 
                        xmlhttp=false; 
} 
} 
} 

return xmlhttp; 
} 

function getState(countryId) {     

var strURL="findState.php?country="+countryId; 
var req = getXMLHTTP(); 

if (req) { 

req.onreadystatechange = function() { 
if (req.readyState == 4) { 
// only if "OK" 
                       if (req.status == 200) {                     
                          document.getElementById('statediv').innerHTML=req.responseText; 
                          document.getElementById('citydiv').innerHTML='<select name="city">'+ 
                          '<option>Select City</option>'+ 
                     '</select>';                     
} else { 
alert("Problem while using XMLHTTP:\n" + req.statusText); 
} 
                   }                
               }            
req.open("GET", strURL, true); 
req.send(null); 
}        
} 
function getCity(countryId,stateId) {      
var strURL="findCity.php?country="+countryId+"&state="+stateId; 
var req = getXMLHTTP(); 

if (req) { 

req.onreadystatechange = function() { 
if (req.readyState == 4) { 
// only if "OK" 
if (req.status == 200) {                     
                           document.getElementById('citydiv').innerHTML=req.responseText;                      
} else { 
                          alert("Problem while using XMLHTTP:\n" + req.statusText); 
                       } 
}                
               }            
req.open("GET", strURL, true); 
req.send(null); 
} 

} 
</script> 

<style type="text/css"> 
body {font-family: Arial, "Trebuchet MS";font-size: 17px;color: #52B6EB; } 
a{font-weight: bold;letter-spacing: -1px;color: #52B6EB;text-decoration:none;} 
a:hover{color: #99A607;text-decoration:underline;} 
#top{width:43%;margin-top: 25px; height:60px; border:1px solid #BBBBBB; padding:10px;} 
#tutorialHead{width:43%;margin-top: 12px; height:30px; border:1px solid #BBBBBB; padding:11px;} 
.tutorialTitle{width:95%;float:left;color:#99A607} 
.tutorialTitle a{float:right;margin-left:20px;} 
.tutorialLink{float:right;} 
table 
{ 
margin-top:70px; 
border: 1px solid #BBBBBB; 
padding:25px; 
height: 35px; 
} 
</style> 
</head> 
<body> 
<form method="post" action="insert.php" name="form1"> 
<center> 
<div id='top'> 
     <a href="http://www.technaitra.com" title="Technaitra Solutions" target="blank"> 
      <img src="image/mainlogo.png" alt="Technaitra Solutions" title="Technaitra Solutions" border="0"/> 
     </a> 
</div> 

    <div id='tutorialHead'> 
     <div class="tutorialTitle"><b>Country State City Dropdown Using Ajax</b> 
      <a href="http://phpwithsmile.blogspot.in" title="Country State City Dropdown Using Ajax">Tutorial Link</a> 
    </div> 
</div> 


<table width="45%" cellspacing="0" cellpadding="0"> 
    <tr> 
    <td width="75">Country</td> 
    <td width="50">:</td> 
    <td width="150"><select name="country" onChange="getState(this.value)"> 
       <option value="">Select Country</option> 
       <?php while ($row=mysql_fetch_array($result)) { ?> 
       <option value=<?php echo $row['id']?>><?php echo $row['country']?></option> 
       <?php } ?> 
       </select></td> 
    </tr> 
    <tr style=""> 
    <td>State</td> 
    <td width="50">:</td> 
    <td ><div id="statediv"><select name="state" > 
       <option>Select State</option> 
     </select></div></td> 
    </tr> 
    <tr style=""> 
    <td>City</td> 
    <td width="50">:</td> 
    <td ><div id="citydiv"><select name="city"> 
       <option>Select City</option> 
     </select></div></td> 
    </tr> 

</table> 
</center> 

<input name="Submit" type="Submit" value="Submit"> 

</form> 
</body> 
</html> 

創建文件findstate.php和粘貼下面的代碼:

<?php 
error_reporting(0); 

$country=intval($_GET['country']); 
$con = mysql_connect('localhost', 'root', ''); 
if (!$con) { 
    die('Could not connect: ' . mysql_error()); 
} 
mysql_select_db('prem'); 
$query="SELECT id,statename FROM state WHERE countryid='$country'"; 
$result=mysql_query($query); 

?> 
<select name="state" onchange="getCity(<?php echo $country?>,this.value)"> 
<option>Select State</option> 
<?php while ($row=mysql_fetch_array($result)) { ?> 
<option value=<?php echo $row['id']?>><?php echo $row['statename']?></option> 
<?php } ?> 
</select> 

創建文件findcity.php和粘貼下面的代碼:

<?php 
error_reporting(0); 

$countryId=intval($_GET['country']); 
$stateId=intval($_GET['state']); 
$con = mysql_connect('localhost', 'root', ''); 
if (!$con) { 
    die('Could not connect: ' . mysql_error()); 
} 
mysql_select_db('prem'); 
$query="SELECT id,city FROM city WHERE countryid='$countryId' AND stateid='$stateId'"; 
$result=mysql_query($query); 

?> 
<select name="city"> 
<option>Select City</option> 
<?php while($row=mysql_fetch_array($result)) { ?> 
<option value=<?php echo $row['id']?>><?php echo $row['city']?></option> 
<?php } ?> 
</select> 

創建文件insert.php和粘貼下面的代碼:

<html> 
<head> 
<title>Untitled Document</title> 
</head> 
<body> 
<?php 
error_reporting(0); 

$con = mysql_connect("localhost","root",""); 
if (!$con) 
    { 
    die('Could not connect: ' . mysql_error()); 
    } 

mysql_select_db("prem", $con); 

$sql="INSERT INTO result (country,state,city) 
VALUES 
('$_POST[country]','$_POST[state]','$_POST[city]')"; 

if (!mysql_query($sql,$con)) 
    { 
    die('Error: ' . mysql_error()); 
    } 
echo "1 record added"; 

mysql_close($con); 
?> 

</body> 
</html> 

數據庫文件: 與名炳創建數據庫並粘貼到SQL如下: /*創建表的國家*/

CREATE TABLE `country` (
    `id` tinyint(4) NOT NULL auto_increment, 
    `country` varchar(20) NOT NULL default '', 
    PRIMARY KEY (`id`) 
) 

/創建表的狀態/

CREATE TABLE `state` (
    `id` tinyint(4) NOT NULL auto_increment, 
    `countryid` tinyint(4) NOT NULL, 
    `statename` varchar(40) NOT NULL, 
    PRIMARY KEY (`id`) 
) 

/*創建表城市*/

CREATE TABLE `city` (
    `id` tinyint(4) NOT NULL auto_increment, 
    `city` varchar(50) default NULL, 
    `stateid` tinyint(4) default NULL, 
    `countryid` tinyint(4) NOT NULL, 
    PRIMARY KEY (`id`) 
) 

/*記錄插入country表中*/

INSERT INTO `country` VALUES (1, 'USA'); 
INSERT INTO `country` VALUES (2, 'Canada'); 

/*記錄插入到狀態表*/

INSERT INTO `state` VALUES (1, 1, 'New York'); 
INSERT INTO `state` VALUES (2, 1, 'Los Angeles'); 
INSERT INTO `state` VALUES (3, 2, 'British Columbia'); 
INSERT INTO `state` VALUES (4, 2, 'Toranto'); 

/*記錄插入城市表*/

INSERT INTO `city` VALUES (1, 'Los Angales', 2, 1); 
INSERT INTO `city` VALUES (2, 'New York', 1, 1); 
INSERT INTO `city` VALUES (3, 'Toranto', 4, 2); 
INSERT INTO `city` VALUES (4, 'Vancovour', 3, 2); 

/*創建表結果*/

CREATE TABLE `result` (
    `id` tinyint(4) NOT NULL auto_increment, 
    `city` varchar(50) default NULL, 
    `state` varchar(50) default NULL, 
`country` varchar(50) default NULL, 
    PRIMARY KEY (`id`) 
)