我收到类型错误:未定义javascript代码。我正在尝试使用jquery与mysql服务器发送的数据填充下拉列表。
这是javascript代码
$(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) {
console.log(data.d);
option += '<option>' + value.arr + '</option>';
});
$('#timing').html(option);
}
});
});
});
这是从mysql数据库中获取数据的php脚本
$doctor = $_POST['doctor'];
$day = $_POST['day'];
$query="SELECT * FROM schedule WHERE doctor='$doctor' AND day='$day'";
$arr = array();
$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);
array_push($arr, $index[$res]);
}
$i++;
}
答案 0 :(得分:4)
您没有以正确的方式使用each()替换
$.each(data.d, function(index, value) {
通过
if(data.d)
{
$(data.d).each(function(index, value) {
// your code
php 中的使用json_encode()将您的数据设为 json
} // end of while
echo json_encode($arr);
更新了代码,尝试 php脚本,
$i = 0;
//Initialize the variable which passes over the array key values
while($row = mysqli_fetch_assoc($result))
{
$arr['d'][$i]=$row['doctor'];
// you can add more fields in array like above
$i++;
}
echo json_encode($arr);
return;
Javascript 中的在阅读DOC jquery.each()
之后会有效 $.each(data.d, function(index, value) {
option += '<option>' + value+ '</option>';
});
答案 1 :(得分:0)
您似乎没有解析JSON,请尝试以下操作,请注意
行 data = JSON.parse(data);
您必须在数据对象上使用JSON.parse,否则JavaScript会将其视为字符串。
$(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 = '';
data = JSON.parse(data);
$.each(data.d, function(index, value) {
console.log(data.d);
option += '<option>' + value.arr + '</option>';
});
$('#timing').html(option);
}
});