javascript - 如何使用 jquery 在 $.Ajax() Success 上创建 DOM 元素?

标签 javascript jquery ajax

我正在 $.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" />&nbsp;<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" />&nbsp;<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/

相关文章:

javascript - 当按钮为空时,按钮尺寸会变得太小

javascript - 从 php 到 javascript 的增值税验证

javascript - 当索引位于不同数组中时遍历 JSON 数据

jquery - 使用 jQuery validate 验证字段组

javascript - Laravel Ajax - 未捕获的 ReferenceError : KWS1389776 is not defined at HTMLButtonElement. onclick

php - 在服务器中保存一个 javascript 字符串

javascript - 我应该使用多个 Canvas (HTML 5) 还是使用 div 来显示 HUD 数据?

javascript - 根据输入范围值显示/隐藏 DOM 元素

jquery - 如何获取图像高度属性

jquery - Asp.net MVC Core - 无法使用 Ajax 加载部分 View