dragon88112 2011-01-18 11:35
浏览 92
已采纳

Ajax方法根据第一个选择填充第二个动态下拉列表

I've not used much Ajax before, and this seems simple. I have the seperate parts to the puzzle, but not sure how to put them together.

Both dropdowns are populated from the database, the first is populated using the following code:

<?php
$sql = "SELECT title, nid FROM node where type= 'hotel'";
$hotels = mysql_query($sql);
?>
<select name="hotels" id="hotels">
<?php
while($row = mysql_fetch_array($hotels))
{
  echo "<option value=\"".$row['nid']."\">".$row['title']."
  ";
}
?>
</select>

The second dropdown should be populated based on the value selected above. So basically I want to take the id of the selected item and then use that in a query to populate the second dropdown.

I would use the above code, but with the following for the SQL query:

SELECT title, nid from node where type = 'season' AND hotel_nid = X

Where X is the id of the selectedIndex on the first dropdown.

Althought the code is there to work, I don't know how to combine the two. I could use Javascript to modify the InnerHTML of a div called "seasons" by printing the code to retrieve and display the dropdowns.

But is there a better way where I can have both the dropdowns visible, but the second is disabled until the first is completed?

  • 写回答

2条回答 默认 最新

  • duanhai4046 2011-01-18 11:55
    关注

    Your PHP script populating the second list should be called through Ajax when the user changes the value of the first dropdown. So you should add onchange="myFunctionToPopulate(this.value);" to the first dropdown.

    If you don't know how to do that I'd suggest also you use a JS library such as jQuery, and we will post you the simple code to achieve this.

    Edited

    With jQuery, you can do something like this:

    <select name="first_dropdown" onchange="$('#dropdown2_container').load('your_script.php?nid='+this.value);">
      <option....
    </select>
    ...
    <div id="dropdown2_container" style="display:none"> </div>
    

    Where your_script.php would return the whole select tag.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 求学软件的前人们指明方向🥺
  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥15 MCNP里如何定义多个源?
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services