我需要调用两个带有一个函数的模板,当两个ajax调用数据成功并注入带有胡子的模板时,然后才调用此函数。我相信我可以用with和then声明做到这一点,但我对它的使用有点迷失。请任何帮助都很棒,谢谢。
我的JavaScript(原始问题):
function ajax(){
$.ajax({
url: "js/projects.js",
dataType:'json',
data: dataId,
success:function(response){
var data = response.employees[dataId];
var template = $('#projectbig_tmp').html();
var html = Mustache.to_html(template, data);
$('.projects').html(html);
console.log(data);
}
});
$.ajax({
url: "js/projects.js",
dataType:'json',
data: dataId,
success:function(response){
var data = response.employees[dataId];
var template = $('#projectHeader_tmp').html();
var html = Mustache.to_html(template, data);
$('.projects').html(html);
console.log(data);
}
});
$.when({
//both ajax request are succesfull with returned data perform this function().
});
}
$("#header").on('click', ajax);
}());
最终工作解决方案代码:
function ajax(){
alert('crackers');
var request1 = $.ajax({
url: "js/projects.js",
dataType:'json',
}).then(function(response){
var data = response.employees[1];
var template = $('#projectbig_tmp').html();
var project = Mustache.to_html(template, data);
console.log(typeof(project));
return project;
});
var request2 = $.ajax({
url: "js/projects.js",
dataType:'json',
}).then(function(response){
var data = response.employees[1];
var template = $('#projectHeader_tmp').html();
var projectHeader = Mustache.to_html(template, data);
console.log(projectHeader);
return projectHeader;
});
$.when(request1, request2).then(function(t,r) {
$('.projects').html(t).prepend(r);
});
}
$("#header").on('click', ajax);
}());
答案 0 :(得分:4)
将每个return
调用的$.ajax
值分配给变量:
var request1 = $.ajax(...);
var request2 = $.ajax(...);
$.when(request1, request2).then(function() {
// called when both are complete
});
由于您希望在将响应添加到DOM之前预先处理响应,因此您应该使用链式success
调用替换单个.then
处理程序,例如: (第一次电话会议):
var request1 = $.ajax(...).then(function(response) {
var data = response.employees[1];
var template = $('#projectbig_tmp').html();
return Mustache.to_html(template, data);
});
此时,它将被模板替换的值传递给最终的$.when().then(...)
回调而不是整个原始响应。当然,您必须声明参数:
$.when(request1, request2).then(function(project, projectHeader) { ... });