我正在 $.ajax
上创建 checkbox
的动态列表:
function load() {
$.ajax({
type: "POST",
url: "*************",
data: "************",
dataType: "json",
contentType: "application/json; charset=utf-8",
error: function (x, e) { alert(e.responseText); },
success: function (objTrendList) {
$.each(objTrendList, function (index, value) {
// append the checkbox panels to tool div
$('#tools').append('<input type="checkbox" id="checkbox_' +
value.LngTrendID + '" checked="checked" value="0" /> <div
style="display:inline;">' + value.StrTrendName + '</div><br />');
});
}
});
}
$(document).ready(function () {
load();
console.log($('#tools :checkbox')); // i know I don't get any thing here
because the this line is called before the ajax function
});
我知道我对 console.log 行没有任何了解,因为该行是在 ajax 函数之前调用的
问题 我如何才能首先加载 ajax 函数,尽管当我执行 $(document).ready()
时它将最后运行
谢谢
最佳答案
返回 ajax 调用并使用 $.ajax 中已经内置的延迟对象:
function load() {
return $.ajax({
type: "POST",
url: "*************",
data: "************",
dataType: "json",
contentType: "application/json; charset=utf-8",
error: function (x, e) { alert(e.responseText); },
success: function (objTrendList) {
$.each(objTrendList, function (index, value) {
// append the checkbox panels to tool div
$('#tools').append('<input type="checkbox" id="checkbox_' +
value.LngTrendID + '" checked="checked" value="0" /> <div
style="display:inline;">' + value.StrTrendName + '</div><br />');
});
}
});
}
$(document).ready(function () {
load().done(function() {
console.log($('#tools :checkbox')); // i know I don't get any thing here
});
});
关于javascript - 如何使用 jquery 在 $.Ajax() Success 上创建 DOM 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14610180/