我通过Ajax(品牌列表)加载SELECT元素,获取其选择的值(品牌ID),并通过另一个Ajax URL(当前所选品牌的模板列表)加载另一个SELECT。

这是我的代码:

$(document).ready( function() {


    // DO NOT cache Ajax calls
    $.ajaxSetup ({ cache: false });

    // loader
    var ajax_load = "Loading...";

    //  Brands List URL
    var loadBrandUrl = "getBrandsList.php";
    //  Templates List URL
    var loadTemplateUrl = "getTemplatesList.php";

    $("#brandslistSelect").html(ajax_load).load(loadBrandUrl)
        .ajaxComplete(function(){  // Brands select loaded

        /* Load Templates SELECT the first time since no .change() has happened */
            var selectedBrand = $("#brandslistSelect option:selected").attr("value");  // get the value
            console.log(selectedBrand);  // Log selected brand to console
            // get Templates select, commented for now since it does an infinite loop
            // $("#templateslistSelect").html(ajax_load).load(loadTemplateUrl, { BrandId: selectedBrand } );
        /* End initial load template */

        /* On interaction with the Brands SELECT */
        $("#brandslistSelect").change(function () {  // on interaction with select

            selectedBrand = $("#brandslistSelect option:selected").attr("value");  // get the value
            // get Templates SELECT
            $("#templateslistSelect").html(ajax_load).load(loadTemplateUrl, { BrandId: selectedBrand } )
        });
        /* End interaction with the Brands SELECT */

    });


});


它在控制台中返回3次selectedBrand:
selectedBrand =未定义
selectedBrand =未定义
selectedBrand = 101

现在,如果我取消注释以下行,则输出与上述相同,但它还会无限期地加载模板URL:

// $("#templateslistSelect").html(ajax_load).load(loadTemplateUrl, { BrandId: selectedBrand } );




知道如何修改此代码以使其按预期工作吗?

感谢您对stackOverflow社区的帮助!

最佳答案

如果将函数作为.load()的第二个参数传递,会得到相同的效果吗?听起来由于某种原因,在HTML完成加载之前就调用了log代码,这就是为什么它找不到select的原因。几乎每次下载数据块时(而不是在整个过程之后)都像调用ajaxComplete()一样“感觉”。

$("#brandslistSelect").html(ajax_load);
$("#brandslistSelect").load(loadBrandUrl, function(){  // Brands select loaded

    /* Load Templates SELECT the first time since no .change() has happened */
        var selectedBrand = $("#brandslistSelect option:selected").attr("value");  // get the value
        console.log(selectedBrand);  // Log selected brand to console
        // get Templates select, commented for now since it does an infinite loop
        // $("#templateslistSelect").html(ajax_load).load(loadTemplateUrl, { BrandId: selectedBrand } );
    /* End initial load template */

    /* On interaction with the Brands SELECT */
    $("#brandslistSelect").change(function () {
        // on interaction with select
        selectedBrand = $("#brandslistSelect option:selected").attr("value");  // get the value
        // get Templates SELECT
        $("#templateslistSelect").html(ajax_load);
        $("#templateslistSelect").load(loadTemplateUrl, { BrandId: selectedBrand } );
    });
    /* End interaction with the Brands SELECT */

})

09-25 17:03
查看更多