嗨 我试图调用两个用户定义的函数,并期望第一个函数必须先执行,然后是第二个……但它们是同时执行的。
$.firstfunc = function(){
//Do something
//jQuery.ajax({
});
$.secondfunc = function(){
//Do something
jQuery.ajax({
});
$.(document).ready(function(){
$.firstfunc();
$.secondfunc();
});
如有任何帮助,我们将不胜感激。
谢谢!
最佳答案
警告:需要 jQuery 1.5+
$.firstfunc = function() {
return $.ajax({});
}
$.secondfunc = function() {
return $.ajax({});
}
$(function() {
$.when($.firstfunc).then($.secondfunc);
});
使用 $.Deferred
的黑魔法的和 $.when
.
它基本上是说当你的第一个函数完成其 ajax 调用时,然后调用第二个函数。
这是因为$.ajax
返回 jqXHR
继承自 $.Deferred
的对象。
如果您想在 $.firstfunc
和 $.secondfunc
完成时附加回调,则可以执行以下操作(需要 jQuery 1.6):
$(function() {
$.first().pipe($.second).done(function(second_data) {
// both finished.
});
});
旧版: jQuery 1.4.2 和 1.3.2 支持。
$.firstfunc = function(cb) {
$.ajax({
success: function() {
...
cb();
},
...
});
}
$.secondfunc = ...
$(function() {
$.firstfunc($.secondfunc);
});
关于jquery - 在jquery中调用两个用户定义的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6063526/