无法从一个选择框中获取相应的值

时间:2017-08-28 07:00:20

标签: javascript php jquery ajax

我正在进行注册页面,用户在选择其名称时,动态地在“报告头”字段中选择相应的报告头。我已经使用了Ajax,但不知何故报告头字段仍为空。我可以对此有所了解吗?我们将非常感激。

这是我的注册字段,

     <select name="designation" class="form-control" required="" id="desig" >   
             <option selected="selected" >Select your option</option> 
           <?php 
                $sql = mysql_query("SELECT id, designation FROM tbl_designation where id in (1,2,3,4)");
                      while ($row = mysql_fetch_assoc($sql)){   
             echo "<option value=" . $row['id'] . ">" . $row['designation'] . "</option>";
    }
 ?></select>

 <select name="reporting_head" class="form-control"  required="" id="rephead">
          <option selected="selected">Select your option</option>
     </select>

现在我正在申请JavaScript + AJAX,

$(document).ready(function()
{
$("#desig").change(function()
{
var id=$(this).val();
var dataString = 'id='+ id;

$.ajax
({
type: "POST",
url: "ajax_rep.php",
data: dataString,
cache: false,
success: function(html)
{
$("#rephead").html(html);
}
});
});
});

最后是我的ajax_rep.php

 <?php

require("includes/config.php"); 
require("classes/Database.class.php"); 

if($_POST['id'])
{
$id=$_POST['id'];
$sql=mysql_query("SELECT reporting_head_id, reporting_head FROM `tbl_designation` WHERE  id='$id'");
while($row=mysql_fetch_array($sql))
{
$id=$row['reporting_head_id'];
$data=$row['reporting_head'];
echo '<option value="'.$id.'">'.$data.'</option>';
}
}
?>

这是我获得ajax成功的HTML,

 <div class="row row-offcanvas row-offcanvas-right">
 <!--/.col-xs-12.col-sm-9-->
 <div class="col-sm-3 col-md-3 sidebar" id="sidebar">
    <div id="left_panel" class="clearfix left">
      <option value="6">Sales Head</option>

1 个答案:

答案 0 :(得分:0)

中循环尝试
    $list = '<option selected="selected">Select your option</option>';


while($row=mysql_fetch_array($sql))
{
$id=$row['reporting_head_id'];
$data=$row['reporting_head'];
$list .= '<option value="'.$id.'">'.$data.'</option>';
}
}

echo $list;

在你的ajax成功函数中执行此操作

success: function(html)
{
  $("#rephead").html("");
  $("#rephead").append(html);
}