Jquery添加值以选择选项

air*_*air 0 javascript php jquery select

我已经用Google搜索了这个选项很多天但我找不到解决方案.

我想要的是:

  1. 我有两个选择框
  2. 首选框具有国家/地区名称
  3. 第二个选择框为空

我想要的是当我从第一个选择框中选择任何国家(即英国)时,应运行php查询以从表中获取所有城市名称,然后使用Jquery将它们添加到第二个选择框.

谢谢

Lob*_*ity 5

假设

  • 你有一个脚本("/getCities.php"),它接受一个参数("country"),它是你想要城市的国家的ID,并输出如下所示的JSON:

    {"Cities":
    [
        {
            "ID": 1,
            "Name": "New York"
        },
        {
            "ID": 2,
            "Name": "Los Angeles"
        }
    ]}
    
    Run Code Online (Sandbox Code Playgroud)

    (您可以使用JSONLint验证您的JSON.)

那么也许就是这样:

<select id="Countries">
    <!-- omitted -->
</select>
<select id="Cities"></select>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
  $(document).ready(function() {
    // when a new country is selected...
    $("#Countries").change(function() {
      // ...clear existing cities...
      $("#Cities").empty();
      // ...and repopulate cities based on JSON data.
      $.getJSON( "/getCities.php",
      // pass the selected country ID
        {
          country: $("#Countries").val()
        },
        function(data) {
          $.each(data.Cities, function(n, city) {
              // add a new option with the JSON-specified value and text
              $("<option />").attr("value", city.ID).text(city.Name).appendTo("#Cities");
          });
        }
      );
    }); // $("#Countries").change(function() { ... });
  }); // $(document).ready(function() { ... });
</script>
Run Code Online (Sandbox Code Playgroud)