如何根据国家/地区列表使用AJAX填充州名单?

时间:2009-07-26 22:18:15

标签: ajax drop-down-menu

我在下面的代码会在您更改国家/地区列表时更改状态下拉列表 如果选择国家ID号234和224,如何更改状态列表? 如果选择了其他国家/地区,则应将其更改为此文本输入框

<input type="text" name="othstate" value="" class="textBox">

表格

<form method="post" name="form1">
<select style="background-color: #ffffa0" name="country" onchange="getState(this.value)">
<option>Select Country</option>
<option value="223">USA</option>
<option value="224">Canada</option>
<option value="225">England</option>
<option value="226">Ireland</option>
</select>

<select style="background-color: #ffffa0" name="state">
<option>Select Country First</option>
</select>

javascript

<script>
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;
     } else {
       alert("There was a problem while using XMLHTTP:\n" + req.statusText);
     }
       }
      }
   req.open("GET", strURL, true);
   req.send(null);
   }
}
</script>

6 个答案:

答案 0 :(得分:5)

只需在执行AJAX请求之前检查countryId值,并仅在countryId处于允许范围内时执行请求。在countryId不匹配的情况下,我会隐藏选择(也可能清除它的值)并显示之前隐藏的已存在的输入。如果选择了允许的国家,则应该采取相反的措施。

下面的jQuery示例:

<form method="post" name="form1">
   <select style="background-color: #ffffa0" name="country" onchange="getState(this.value)">
      <option>Select Country</option>
      <option value="223">USA</option>
      <option value="224">Canada</option>
      <option value="225">England</option>
      <option value="226">Ireland</option>
   </select>

   <select style="background-color: #ffffa0" name="state">
      <option>Select Country First</option>
   </select>

   <input type="text" name="othstate" value="" class="textBox" style="display: none;">
</form>

$(function() {
    $('#country').change( function() {
        var val = $(this).val();
        if (val == 223 || val == 224) {
            $('#othstate').val('').hide();
            $.ajax({
               url: 'findState.php',
               dataType: 'html',
               data: { country : val },
               success: function(data) {
                   $('#state').html( data );
               }
            });
        }
        else {
           $('#state').val('').hide();
           $('#othstate').show();
        }
    });
});

答案 1 :(得分:1)

我认为简单的做法是提供一个状态下拉列表和一个包含不同ID的文本输入框。将两者的显示设置为,然后您只需要用

包围getState()的内容
if (countryId == 233 || countryId == 234) {
   /* Ajax state population here */

   dropdownId.display = 'block';
   textEntryId.display = 'none';
}
else  {
   textEntryId.display = 'block';
   dropdownId.display = 'none';
}

(其中dropdownIdtextEntryId是相关UI组件的ID),因此您可以在选择时启用/显示状态下拉列表或文本条目的显示。

JQuery一切都很好,但我不会介绍只是来解决这个问题。

答案 2 :(得分:1)

编辑:这是一个非常适合任务的解决方案,适应了Tvanfosson的界限:

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js">
</script>

<script>
$(function() {
  $('#country').change( function() {
    var val = $(this).val();
    if (val == 223 || val == 224) {
        $('#othstate').val('').hide();
        $.ajax({
           url: 'findState.php',
           dataType: 'html',
           data: { country : val },
           success: function(data) {
               $('#state').html( data );
           }
        });
    }
    else {
       $('#state').val('').hide();
       $('#othstate').show();
    }
  });
});
</script>

<select style="background-color: #ffffa0" name="country" id=country >
  <option>Select Country</option>
  <option value="223">USA</option>
  <option value="224">Canada</option>
  <option value="225">England</option>
  <option value="226">Ireland</option>
</select>

<select style="background-color: #ffffa0" name="state">
  <option>Select Country First</option>
</select>

<input type="text" name="othstate" id=othstate value="" class="textBox" style="display: none;">

正如您所看到的,我删除了<form>元素,这不是绝对必要但可以添加(如果在用户端停用JS,则必须正确使用。) here

我还删除了被'change()`jquery函数替换的onchange事件。

答案 3 :(得分:0)

VK API只需选择国家/地区,获取ID并从

中选择城市

&#13;
&#13;
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="http://code.jquery.com/jquery-latest.js"></script>

<script type="text/javascript">
    
var $j = jQuery.noConflict();
var _getCountry = function() {
    $j.ajax({
      url: "http://api.vk.com/method/database.getCountries",
      data: {
       'v': 5.5,
        'need_all': 0,
        'code' : 'RU,UA,BY,KZ,KG,LV,EE'  
       // 'count': 10
      },
      dataType: 'jsonp',
      success: function(data, status) {
        if (status !== 'success') {
          return false;
        }
        console.log(data.response, status); 
          
        $j.each(data.response.items, function(i, item) {
         console.log("each country");
         var newOption = '<option id="' + item.id + '" value="' + item.title + '">' + item.title + '</option>';
         country_options.push(newOption);
       });
    
       document.getElementById('countrylist').innerHTML = country_options;
          
      }
        
 });  
 }   

var _getCity = function(country_id) {
     
    $j.ajax({
      url: "http://api.vk.com/method/database.getCities",
      data: {
       'v': 5.61,
        'need_all': 0,
        'country_id': country_id
      },
      dataType: 'jsonp',
      success: function(data, status) {
        if (status !== 'success') {
          return false;
        }
        console.log(data.response, status); 
          
        $j.each(data.response.items, function(i, item) {
         console.log("each city");
         var newOption = '<option id="' + item.id + '" value="' + item.title + '">' + item.title + '</option>';
         city_options.push(newOption);
       });
    
       document.getElementById('citylist').innerHTML = city_options;
          
      }
        
 });  
 }  
       
var  city_options = [];
var  country_options = [];
    
 $j(document).ready(function () {  
    _getCountry(); 
     
  $j('#country').on('input',function() {
    var opt = $j('option[value="'+$j(this).val()+'"]');
    var countryid = opt.attr('id');  
      
    _getCity(countryid);  
      
     
  });

  
 });

</script>
&#13;
 <div class="form-group">
          <label class="col-lg-4 control-label">Страна:</label>
          <div class="col-lg-8">
          
              <div class="controls">
            	<input name="country" list="countrylist" id="country" class="form-control" />
                <datalist id="countrylist">
                </datalist> 
              </div>
        
           
           
            
          </div>
        </div> 
   
        <div class="form-group">
          <label class="col-lg-4 control-label">Город:</label>
          <div class="col-lg-8">
                
            <input name="city" list="citylist" id="city" class="form-control"/>
                <datalist id="citylist">
            </datalist>  
              
           
          </div>
        </div> 
&#13;
&#13;
&#13;

答案 4 :(得分:0)

////////////////// connection file con.php rishabh
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
         $dbhost = 'localhost';
         $dbuser = 'root';
         $dbpass = '';
         $conn = mysql_connect($dbhost, $dbuser, $dbpass);
         if(! $conn ) {
            die('Could not connect: ' . mysql_error());
         }
         mysql_select_db( 'testajax' );
?>

/////////////////////////// index.php rishabh
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<?php 
include('con.php');
?>
<form>
<div class="frmDronpDown">
    <div class="row">
        <table><tr><td><label>Country:</label><br/>
        <select name="country" id="country" data-name="country" class="demoInputBox" onChange="getCountry(this.value);">
        <option value="">Select Country</option>
        <?php
         $sql = mysql_query("SELECT distinct country FROM statecont ");
     while($result=mysql_fetch_array($sql)){
        ?>
        <option value="<?php echo $result['country']; ?>"><?php echo $result['country']; ?></option>
        <?php
        }
        ?>
        </select> </td>
             <td>
<label>Phone:</label><br/>
        <select name="phone" id="phone" data-name="phone" class="demoInputBox" onChange="getPhone(this.value);">
        <option value="">Select Country</option>
        <?php
         $sql = mysql_query("SELECT distinct phone FROM statecont ");
     while($result=mysql_fetch_array($sql)){
        ?>
        <option value="<?php echo $result['phone']; ?>"><?php echo $result['phone']; ?></option>
        <?php
        }
        ?>
        </select> 
</td></tr></table>
    </div>
    <div id="state-list"></div>
</div>
</form>
<script>
function getCountry(val) {
        var dataname = $('#country').attr('data-name');

        console.log(dataname);
    $.ajax({
    type: "POST",
    url: "data.php",
        data: {
                value_name: val,
                colomn_name: dataname
                },
    success: function (data){
        $("#state-list").html(data);
    }
    });
}

function getPhone(val) {
        var dataname = $('#phone').attr('data-name');

    console.log(dataname);
    $.ajax({
    type: "POST",
    url: "data.php",
        data: {
                 value_name: val,
                colomn_name: dataname
                },
    success: function (data){
        $("#state-list").html(data);
    }
    });
}
</script>

// ////////////////////data file data.php rishabh
<?php 
$val = $_POST["value_name"]; 
$colomn = $_POST["colomn_name"]; 
include('con.php');
$sql_aa = mysql_query("SELECT * FROM statecont where ".$colomn."='$val'"); ?>
  <table>
<tr><td>State</td><td>Countery</td></tr>
<?php while($result_aa=mysql_fetch_array($sql_aa)){ ?>
<tr><td><?php echo $result_aa['state']; ?></td><td><?php echo $result_aa['country']; ?></td></tr>
<?php } ?>
</table>

答案 5 :(得分:0)

**index.html**
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Populate City Dropdown Using jQuery Ajax</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
    $("select.country").change(function(){
        var selectedCountry = $(".country option:selected").val();
        $.ajax({
            type: "POST",
            url: "ajaxServer.jsp",
            data: { country : selectedCountry } 
        }).done(function(data){
            $("#response").html(data);
        });
    });
});
</script>
<style>
select { width: 10em }
</style>
</head>
<body>
<form>
    <table>
        <tr>
            <td> <label>Country:</label></td>
            <td>    <select class="country">
                    <option>Select</option>
                    <option value="usa">United States</option>
                    <option value="india">India</option>
                    <option value="uk">United Kingdom</option>
                </select>
            </td>
        </tr>
        <tr><td >
        <label>States:</label></td>
     <td>   <select id="response">
                    <option>Select State</option>

                </select>
        </td></tr>

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

**ajaxServer.jsp**
<option>Select State</option>
<% 
String count=request.getParameter("country");
String india[]={"Mumbai", "New Delhi", "Bangalore"};
String usa[]={"New Yourk", "Los Angeles","California"};
String uk[]={"London", "Manchester", "Liverpool"};
String states[];
if(count.equals("india"))
{
    for(int i=0;i<=2;i++)
    {
    out.print("<option>"+india[i]+"</option>");
    }
}
else if(count.equals("usa"))
{
    for(int i=0;i<usa.length;i++)
    {
    out.print("<option>"+usa[i]+"</option>");
    }
}
else if(count.equals("uk"))
{
    for(int i=0;i<=2;i++)
    {
    out.print("<option>"+uk[i]+"</option>");
    }
}

%>