我试图延迟从jstree插件执行jQuery函数,直到另一个函数(替换目标html id)在方法时使用jQuery完成。但是,以下脚本似乎没有做对。
想法是让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;
}
});
}
});
}
答案 0 :(得分:0)
承诺:
loadxml().then(function() {
$('#jstree').jstree();
});
function loadxml(){
return $.ajax({/* parameters */})
.then(function(catxml) {
//code that runs on the result of the first ajax request
//return the promise from the next ajax request
return $.ajax({/* parameters */})
})
.then(function(prodxml) {
//code that runs on the result of the second ajax request
});
}
答案 1 :(得分:-1)
递延
$.when(loadxml()).then(function(){
$('#jstree').jstree();
});
function loadxml(){
var deferred = $.Deferred();
$.ajax({
success : function(){
//code
$.ajax({
success: function(){
//your code
deferred.resolve();
}
})
}
})
return deferred.promise();
}
});