我知道AJAX是异步工作的(即“A”代表的)。我在成功回调中移动了所有依赖于AJAX调用结果的代码。然而,在进行调用之后,我没有让select dropdwon框填充任何数据。如何在ajax调用后填充选择下拉菜单?
的Jquery / AJAX
<script>
function showFields(option){
var content = '';
for (var i = 1; i <= option; i++){
function addNewCourse() {
var data;
$.ajax({
type: "POST",
url: "coursesOffered.php",
data: { value : option},
success: function(data){
//alert(data);
//console.log(data);
content += '<select id="coursename_'+i+'" name="coursename_'+i+'" class="course_list"><option value="" >--- Select ---</option>"';
content += data;
content += '</select></br>';
}
});
}
addNewCourse();
}
}
</script>
coursesOffered.php
try {
$db_con = new PDO($dsn, $user, $password);
$db_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$course_query = $db_con->prepare("SELECT course_id, course_name FROM courses_selection_list;");
$course_query->execute();
$data = $course_query->fetchAll();
foreach ($data as $row){
//dropdown values pulled from database
echo '<option value="' . $row['course_id'] . ':'.$row['course_name'].'">' . $row['course_name'] . '</option>';
}
答案 0 :(得分:1)
在代码中查看我的评论:
function showFields(option) {
for (var i = 1; i <= option; i++) {
(function(i) {
$.ajax({
type: "POST",
url: "coursesOffered.php",
data: {
value: option
},
success: function (data) {
var content += '<select id="coursename_' + i + '" name="coursename_' + i + '" class="course_list"><option value="" >--- Select ---</option>"';
content += data;
content += '</select></br>';
// Insert the `content` into DOM here, you cannot return due to the async nature of AJAX
}
});
})(i); // you have to pass `i` into a function, otherwise when ajax complete, i will equal to `option + 1`
}
}
答案 1 :(得分:0)
似乎你没有在addNewCourse()中使用return语句,在完成Ajax后尝试return content;
。
$(document).ready(function () {
$('#courses_offered').change(function() {
var option = $(this).val();
showFields(option);
return false;
});
function showFields(option){
var content = '';
for (var i = 1; i <= option; i++){
function addNewCourse() {
$.ajax({
type: "POST",
url: "coursesOffered.php",
data: { value : option},
success: function(data){
content += '<div id="course_'+i+'"><label>Course # '+i+'</label><br /><label>Course Name:</label> <select id="coursename_'+i+'" name="coursename_'+i+'" class="course_list"><option value="" >--- Select ---</option>"';
content += data;
content += '</select></div></br>';
}
});
return content;
}
content = addNewCourse();
}
$('#course_catalog').html(content);
}
});