我尝试在文档加载或准备好后从数据库中的值填充选择框。我是ajax和jquery的新手,有人可以帮我找到我的代码有什么问题吗?
<select class="form-control sec" id="sec" name="sec">
<option value="sec">Section</option>
</select>
这是我的ajax代码。
function loadselectbox(){
var fac_code = $("#faculty_code").val();
$.ajax({
type: 'POST',
url: 'getrecords.php',
data: {
"load": 1,
"fac_code": fac_code
},
dataType: 'json',
success: function(data)
{
var select = $("#sec"), options = '';
for(var i=0;i<data.length; i++)
{
options += "<option value='"+data[i].section+"'>";
}
select.append(options);
}
});
}
这是我的getrecords.php
if (isset($_POST['load'])) {
$fac_code = $_POST['fac_code'];
$select = mysqli_query($con,"SELECT * FROM tfile WHERE faculty_code = '$fac_code'");
while ($row = mysql_fetch_array($select)) {
$result[] = array(
'section' => $row['section'],
'subj_descr' => $row['subj_descr']
);
}
echo json_encode($result);
}
我在document.ready
中调用该函数 $(document).ready(function() {
loaddata();
loadselectbox();
});
答案 0 :(得分:1)
试试这个:
$(document).ready(function(){
var fac_code = $("#faculty_code").val();
$.ajax({
url: 'getrecords.php',
type: 'POST',
data: {
"load": 1,
"fac_code": fac_code
},
success: function(response){ // response contains json object in it
var data = JSON.parse(response);
var options = '<option value=""></option>';
for(var i=0;i<data.length; i++)
{
options += "<option value='"+data[i].section+"'> +data[i].subj_descr+ </option>";
}
$("#sec").html(options); // It will put the dynamic <option> set into the dropdown
}
});
});