Javascript 尝试用jquery和ajax填充下拉列表
这是我的密码:-Javascript 尝试用jquery和ajax填充下拉列表,javascript,php,jquery,Javascript,Php,Jquery,这是我的密码:- <script> $(document).ready(function(){ //#This script uses jquery and ajax it is used to set the values in $("#day").change(function(){ //# the time field whenever a day
<script>
$(document).ready(function(){ //#This script uses jquery and ajax it is used to set the values in
$("#day").change(function(){ //# the time field whenever a day is selected.
var day=$("#day").val();
var doctor=$("#doctor").val();
$.ajax({
type:"post",
url:"time.php",
data:"day="+day+"&doctor="+doctor,
dataType : 'json',
success:function(data){
var option = '';
$.each(data.d, function(index, value) {
option += '<option>' + value.res + '</option>';
});
$('#timing').html(option);
}
});
});
});
</script>
下面是php脚本
<?
$con=mysqli_connect("localhost","clinic","myclinic","myclinic");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$doctor = $_POST['doctor'];
$day = $_POST['day'];
$query="SELECT * FROM schedule WHERE doctor='" .$doctor."'AND day='" .$day. "'";
$result = mysqli_query($con, $query);
$i = 0; //Initialize the variable which passes over the array key values
$row = mysqli_fetch_assoc($result); //Fetches an associative array of the row
$index = array_keys($row); // Fetches an array of keys for the row.
while($row[$index[$i]] != NULL)
{
if($row[$index[$i]] == 1) {
$res = $index[$i];
echo json_encode($res);
}
$i++;
}
?>
我希望在我的html页面上的select中插入带有时间值的选项,该页面如下所示:-
<select id="timing" name="timing"></select>
我的java脚本代码正在将值发布到php脚本中,但代码仍然不起作用。在我看来,我的javascript中没有任何错误。请帮帮我,希望对你有帮助
success:function(data){
var select= '<select>';
var option = '';
$.each(data.d, function(index, value) {
option += '<option>' + value.res + '</option>';
});
select = select+option'</select>';
$('#timing').html(select);
}
HTML:
<div id="timing"> </div>
我想你已经把所有的代码都放在JavaScription中了。你能告诉我们你在成功回调中得到的数据结构吗?我知道变量正在进入php脚本。当我在主页上更改“day”下拉列表中的值时,它会在控制台中弹出。@SilverBlade如何查看数据结构?您能告诉我吗?我是新手:使用console.logdata;
var day=$("#day option:selected").val();
var doctor=$("#doctor option:selected").val();
data:"{day:'"+day+"', doctor: '" + doctor + "'}" ,
var postUrl = "time.php";
$.ajax({
type: "POST",
url: postUrl,
data: {day: day,doctor: doctor},
dataType: "json",
success: function (data) {
$.each(data, function (key, value) {
$('#timing').append('<option value="' + key + '">' + value + '</option>');
});
}
});