在PHP和jQuery中,使一个下拉列表依赖于另一个下拉列表吗? [英] In PHP and jQuery, make one drop-down depend on another drop-down list?

查看:53
本文介绍了在PHP和jQuery中,使一个下拉列表依赖于另一个下拉列表吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个下拉列表,如果选择一个值,另一个则从数据库加载相同的值,则一个依赖于另一个.例如,如果我选择一个国家/地区,而其他国家/地区加载的城市与此国家相同.

I have two drop down lists one is depended on other if one value selected the other one load same values from database. for example if i select one country other load same cities that country.

<select name="A" class="input_text" id="A">

<?php
include 'config/config.php'; 
$sql="SELECT * FROM department ORDER BY Dept ASC";
$result=mysql_query($sql);$options="";
while ($row=mysql_fetch_array($result)){    
$did=$row["DeptCode"];
$depts=$row["Dept"];
$options.="<OPTION value='$did'>".$depts;}?>
 <option value="0">Select...</option>
<?php echo $options; ?>'
 </option>
</select>

<select name="B" class="input_text" id="B">

<?php           
include 'config/config.php'; 
$sql="SELECT * FROM department WHERE DeptCode=$dpttitle";
$result=mysql_query($sql);$options="";
while ($row=mysql_fetch_array($result)){    
$did=$row["DeptCode"];
$depts=$row["Dept"];
$options.="<OPTION value='$did'>".$depts;}?>
<option value="0">Select...</option>
<?php echo $options; ?>
</option>
</select>

<script type="text/javascript">
A.onblur = function() {
 B.value = this.value;};
</script>

推荐答案

您正在寻找"ajax"功能.尝试使用JQuery调查$.get(url,data,success);

You're looking for "ajax" functionality. Try looking into $.get(url,data,success); using JQuery

首先,删除保管箱B并将其替换为id="B"

First, remove dropbox B and replace it with a div with id="B"

$("#A").change(loadCities);
function loadCities(e){
    // prepare get statement
    var url = "http://www.yoursite.com/ajax/getCities";
    var data = {
        country : $("#A").val()
    };
    $.get(url, data, loadCitiesComplete);
}
function loadCitiesComplete(data){
    $("#B").html(data);
}

该网址:"http://www.yoursite.com/ajax/getCities" php应该类似于

That url : "http://www.yoursite.com/ajax/getCities" php should look something like

<?
if(isset($_GET['country'])){
    $html = '<select name="B" class="input_text" id="B">';
    include 'config/config.php'; 
    $dpttitle = mysql_real_escape_string($_GET['country']);
    $sql="SELECT * FROM department WHERE DeptCode=$dpttitle";
    $result=mysql_query($sql);$options="";
    while ($row=mysql_fetch_array($result)){    
    $did=$row["DeptCode"];
    $depts=$row["Dept"];
    $html .="<OPTION value='$did'>".$depts;}?>
    $html .= '<option value="0">Select...</option>';
    $html .= '</option>';
    $html .= '</select>';
    echo $html;
}
?>

很明显,php应该正确使用国家$ _GET var,使用PDO或MySQLi以及为安全起见准备好的语句,等等.但是希望这能使您朝正确的方向发展.

Obviously the php should use the country $_GET var properly, use PDO or MySQLi with prepared statements for safety, etc. But hopefully this'll get you moving in the right direction.

这篇关于在PHP和jQuery中,使一个下拉列表依赖于另一个下拉列表吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆