Ajax方法来填充基于在所述第一选择的第二动态下拉 [英] Ajax approach to populating a second dynamic dropdown based on the selection in the first
问题描述
我没有用太多的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.
这两个下拉菜单从数据库填充,第一个是使用下面的code填充:
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']."\n ";
}
?>
</select>
第二下拉应根据上述选择的值填充。所以基本上我想利用所选项目的ID,然后使用一个查询来填充第二个下拉。
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.
我会用上面的code,但具有下列的SQL查询:
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
其中,X是在第一个下拉列表中的selectedIndex的ID。
Where X is the id of the selectedIndex on the first dropdown.
Althought的code是来工作的,我不知道如何将二者结合起来。我可以使用JavaScript来修改一个名为四季DIV的innerHTML通过打印code来检索和显示的下拉列表。
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?
推荐答案
您的PHP脚本填充第二个列表应通过阿贾克斯当用户更改第一个下拉的值被调用。所以,你应该添加的onchange =myFunctionToPopulate(THIS.VALUE);以第一个下拉。
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.
如果您不知道该怎么做,我也建议你使用JS库,如jQuery的,我们将发布您的简单的code来实现这一目标。
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.
编辑
使用jQuery的,你可以做这样的事情:
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>
在哪里your_script.php将返回整个选择标签。
Where your_script.php would return the whole select tag.
这篇关于Ajax方法来填充基于在所述第一选择的第二动态下拉的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!