使用AJAX,PHP的静态下拉列表

时间:2013-03-07 07:30:51

标签: php ajax

singleselect.html

<html>
  <script>
    function singleselect(str)
    {
      var xmlhttp;
      if(str.length == 0)
      {
        document.getElementById("sing").innerHTML="";
        return;
      }

      if(window.XMLHttpRequest)
      {
         xmlhttp = new XMLHttpRequest();        
      }
      else
      {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
      }

      xmlhtttp.onreadystatechange = function()
      {
        if(xmlhttp.readyState == 4)
        {
          document.getElementById("sing").innerHTML = xmlhttp.responsetext;
        }
      }
      xmlhttp.open("POST","singleselect.php?s=" +str,true);
      xmlhttp.send();
    }
  </script>

  <style>
   div { font-family:verdana; font-size:13px; margin-left:400px; margin-top:100px; }
  </style>
  <body>
    <div>
     Select a country : 
       <select onchange="document(this.value)">
        <option>Select a country</option>
        <option value="0">INDIA</option>
        <option value="1">United States of America</option>
        <option value="2">United Kingdom</option>
        <option value="3">Australia</option>
     </select>
    </div>

    <div id="sing"></div>
  </body>
</html>

singleselect.php

<?php    

$store[0] = "Please select a country";
$store[1] = "Andhra Pradesh";
$store[2] = "New York";
$store[3] = "London";
$store[4] = "Austraila";

$s = $_REQUEST['s'];

?>

当我点击某个国家/地区时,应显示与某个国家/地区相关的状态列表,我希望在php中使用数据库进行静态处理。因为我是jQuery和AJAX。我需要你的指导。

3 个答案:

答案 0 :(得分:0)

如果你想要数组中城市的数据,你可以这样做:

$store[0] = "Please select a country";
$store[1][0] = "Andhra Pradesh";
$store[2][0] = "New York";
$store[3][0] = "London";
$store[4][0] = "Austraila";
$c= $_POST['s'];
if(isset($store[$c]) && is_array($store[$c])){
    foreach($store[$c] as $k=>$v){
        echo $v;
    }
}

答案 1 :(得分:0)

我认为这是你想要的州。最好使用国家代码而不是数字索引。

// states.php 

$states = array (
'IN' => array (
    'indian state',
    'indian state 2'            
    ),
'US' => array (
    'US state',
    'US state 2'
    )
);

$select = '';
if(isset($_POST['s']) && isset($states[$_POST['s']])) {
$select .= '<select name="states">';
foreach($states[$_POST['s']] as $state) {
        $select .= '<option value="' . $state . '">' . $state  . '</option>'; 
}
$select .= '</select>';     
echo $select;
}

答案 2 :(得分:0)

我不确定你想要什么,但据我所知,你想要一个国家下拉列表。所以你需要在singleselect.php

中完成
$state_list = array(
'0' =>  array(
    'state 1',
    'state 2',
    'state 3'
    ),
'1' =>  array(
    'state 4',
    'state 5',
    'state 6'
    ),
'2' =>  array(
    'state 7',
    'state 8',
    'state 9'
    )
);

$select = '<select name="state">';
foreach($state_list[$_REQUEST['s']] as $key => $value) 
{
    $select .= '<option value="'.$key.'">'.$value.'</option>';
}
$select .= '</select>';

echo $select; 

也许它会帮助你。