从DB中获取选择选项的列值

时间:2017-05-11 09:52:24

标签: javascript php jquery mysql ajax

我有一个下拉列表,用于在php页面上选择Id,其值从数据库中获取(第1列)。

下拉列表旁边有一个文本字段,我想在其中显示数据库中成员的名称(第二列)。

代码如下 -

<?php
include ('connection.php');

$query = "SELECT Member_id FROM member_db ORDER BY Member_id ASC";
$result = mysqli_query($conn, $query) or die(mysqli_error($conn)."[".$query."]");
?>
   <Select id="st_id" placeholder="Enter Member id" name="ist_id" required class="styled-select green semi-square onChange="showMember(this.value)"">
      <option selected ="true" disabled="disabled">Select Member Id</option>
<?php while ($row = mysqli_fetch_array($result, MYSQL_ASSOC)){?>
   <option value=" <?php $row['Member_id']; ?> ">
     <?php echo $row['Member_id'];?>
    </option>
<?php }?>
</Select>

<input style="min-height:30px" type="text" id="st_name" placeholder="Member name" name="ist_name" disabled/>

我调用的JavaScript代码是 -

function showMember(str) {
    if (str == "")
    {
        document.getElementById("txtHint").innerHTML = "";
        return;
    }
    else { 
        if (window.XMLHttpRequest)
        {
            // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        }
        else {
            // code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
             }

        xmlhttp.onreadystatechange = function()
        {
            if (this.readyState == 4 && this.status == 200)
            {
                document.getElementById("txtHint").innerHTML = this.responseText;
            }
        };

        xmlhttp.open("GET","getMember.php?q="+str,true);
        xmlhttp.send();
    }
}

getMember.php是另一个php文件,我在其中触发查询以根据Member_id的值获取Member_name。

但问题是,在某种程度上,onChange,页面没有调用showMember()函数。

1 个答案:

答案 0 :(得分:0)

1)在值属性echo

中缺少<option value="<?php $row['Member_id']; ?> "> <?php echo $row['Member_id'];?>

2)onchange应该在class属性之外。<Select id="st_id" placeholder="Enter Member id" name="ist_id" required class="styled-select green semi-square" onChange="showMember(this.value)"> 简单使用jquery ajax

    function showMember(str) 
    {  

     $.ajax({
           url:'getMember.php',
           type:'post',
           data:{q:str},
           success:function(data)
                  {
                    $('#st_name').val(data);
                  }

     });
  }

注意:不要忘记包含jquery