1 回答

TA貢獻(xiàn)1880條經(jīng)驗(yàn) 獲得超4個(gè)贊
使用 jQuery,您可以使用ajax函數(shù)。此函數(shù)使 http 請求在完成時(shí)調(diào)用回調(diào)。有多個(gè)回調(diào)和設(shè)置它們的方法,我建議您查看文檔。在這種情況下,我們使用done
,它僅在請求成功時(shí)才被調(diào)用。
為了在附加選項(xiàng)時(shí)避免字符串插值,我使用第二個(gè)屬性參數(shù)來設(shè)置值和文本。
var form = $("<form></form>");
$("body").append(form)
form.append("<div class='row'></div>");
form.find(".row")
.append("<div class='col-md-6'><div class='form-group'><label class='control-label'>Students</label><select class='form-control' name='students'></select></div></div>");
$.ajax({
url: "path/to/students/endpoint",
dataType: "json", //assuming you return json from you php script
}).done(function (students){
//assuming students is an array of names
var select = form.find('select[name=students]');
for(var name of students) {
select.append($("<option></option>", {
value: name,
text: name
}))
}
})
//Since this is an example and I cant actually make an ajax call
function fakeAjaxResponse(students) {
var select = form.find('select[name=students]');
for(var name of students) {
select.append($("<option></option>", {
value: name,
text: name
}))
}
}
fakeAjaxResponse([
"StudentA",
"StudentB"
])
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
添加回答
舉報(bào)