【发布时间】:2016-05-25 16:22:31
【问题描述】:
我试图延迟 jstree 插件中的 jQuery 函数的执行,直到使用 jQuery when 方法完成另一个函数(替换目标 html id)。但是,下面的脚本似乎不正确。
想法是让 loadxml() 函数完成填充 HTML 树,然后执行 jstree() 函数以应用树视图。
这里是 HTML
<div id="jstree" class= "col-md-6 col-xs-6"></div>
脚本
$.when(loadxml()).then(function(){
$('#jstree').jstree();
});
function loadxml(){
$.ajax({
url: "xml/categories.xml",
dataType: "xml",
success: function(catxml){
var categories = new Array();
var outputDisplay = "";
$(catxml).find("Categories").each( function(){
var cid = $(this).find("CategoryID").text();
var cname = $(this).find("CategoryName").text();
var cdescription = $(this).find("Description").text();
categories.push([cid,cname,cdescription]);
});
$.ajax({
url: "xml/products.xml",
dataType: "xml",
success: function(prodxml){
var products = new Array();
$(prodxml).find("Products").each(function(){
var pid = $(this).find("ProductID").text();
var pname = $(this).find("ProductName").text();
var pcatid = $(this).find("CategoryID").text();
var pquantity = $(this).find("QuantityPerUnit").text();
var pprice = $(this).find("UnitPrice").text();
products.push([pid,pname,pcatid,pquantity,pprice]);
});
outputDisplay += "<ol class='no-bullet'><li>Product List<ol type='i'>"
for(i=0; i<categories.length; i++){
outputDisplay += "<li>" + categories[i][1] + "<ol type='a'>";
for(x=0; x<products.length; x++){
if(categories[i][0] == products[x][2]){
outputDisplay += "<li>" + products[x][1] + "</li>";
}
}
outputDisplay +="</ol></li>";
}
document.getElementById("jstree").innerHTML = outputDisplay;
}
});
}
});
}
【问题讨论】:
-
你的
loadXML函数需要return一个promise,否则when不知道要等什么! -
另外你应该使用
then而不是success,否则它无法知道第二个ajax请求(也不会等待它)。 -
第一次调用
success调用第二个ajax (products.xml),第二次调用成功调用.tree()。 -
嗨,Alex,我已经尝试从第二次成功中调用它,但不幸的是没有运气
标签: javascript jquery .when