[英]How to call a function only after page has finished loading and after another function has been called
[英]Run function inside of another function, but only after ajax has finished
我有一个在另一个函数内部运行的函数,但有时似乎我对服务器的ajax调用在调用该函数之前并未完成运行。
function getPlans(row, user, id, type) {
$.get( "/plans/" + user + "/" + id + "/" + type + "", function(data) {
$("#permissions_" + row + "_plan_type").empty();
$(data).each(function(i, e) {
$("#permissions_" + row + "_plan_type").append("<option>" + e + "</option>");
})
}).done(function() {
getPermissions(row, user, type);
})
}
作为快速解决方案,您可以使用async: false
进行.ajax
调用async: false
function getPlans(row, user, id, type) {
$.ajax({
url:"/plans/" + user + "/" + id + "/" + type + "",
type: 'GET',
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(data) {
$("#permissions_" + row + "_plan_type").empty();
$(data).each(function(i, e) {
$("#permissions_" + row + "_plan_type").append("<option>" + e + "</option>");
})
},
async:false // make synchronous
});
getPermissions(row, user, type);
}
解决方案2:您可以在jQuery中使用.when
。
function getPlans(row, user, id, type) {
var dfd = $.Deferred();
$.when( $.get( "/plans/" + user + "/" + id + "/" + type + ""))
.done(function(data) {
$("#permissions_" + row + "_plan_type").empty();
$(data).each(function(i, e) {
$("#permissions_" + row + "_plan_type").append("<option>" + e + "</option>");
})
});
getPermissions(row, user, type);
}
尝试从成功回调中调用getPermissions()
。
function getPlans(row, user, id, type) {
$.get( "/plans/" + user + "/" + id + "/" + type + "", function(data) {
$("#permissions_" + row + "_plan_type").empty();
$(data).each(function(i, e) {
$("#permissions_" + row + "_plan_type").append("<option>" + e + "</option>");
});
getPermissions(row, user, type);
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.