我通过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 */
});
});
它在控制台中返回selectedBrand 3次:
selectedBrand = undefined
selectedBrand = undefined
selectedBrand = 101
现在,如果我取消注释以下行,输出与上面相同,但它也会无限期地加载模板URL:
// $("#templateslistSelect").html(ajax_load).load(loadTemplateUrl, { BrandId: selectedBrand } );
知道如何修改此代码以使其按预期工作吗?
感谢您的帮助stackOverflow社区!
答案 0 :(得分:1)
如果将函数作为.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 */
})