var ajaxStuff = (function () {
var doAjaxStuff = function() {
//an ajax call
}
return {
doAjaxStuff : doAjaxStuff
}
})();
有没有办法利用这种模式,并在调用我的方法时从成功的ajaxcall获取响应?像这样:
ajaxStuff.doAjaxStuff(successHandler(data){
//data should contain the object fetched by ajax
});
希望你明白这一点,否则我会详细说明。
答案 0 :(得分:3)
两件事: 1.向doAjaxStuff函数添加参数。 2.调用doAjaxStuff时,传入匿名函数(或函数名称)
var ajaxSuff = (function () {
var doAjaxStuff = function(callback) {
// do ajax call, then:
callback(dataFromAjaxCall);
}
return {
doAjaxStuff : doAjaxStuff
}
})();
// calling it:
ajaxStuff.doAjaxStuff(function(data){
//data should contain the object fetched by ajax
});
答案 1 :(得分:1)
让doAjaxStuff
接受回调:
var doAjaxStuff = function(callback) {
// an ajax call
// Inside the Ajax success handler, call
callback(response); // or whatever the variable name is
}
根据您的总体目标,您也可以使用deferred objects代替(或另外)。这使您的代码高度模块化。例如:
var doAjaxStuff = function() {
// $.ajax is just an example, any Ajax related function returns a promise
// object. You can also create your own deferred object.
return $.ajax({...});
}
// calling:
ajaxStuff.doAjaxStuff().done(function(data) {
// ...
});
答案 2 :(得分:0)
我相信您需要阅读jQuery.ajax的jQuery文档。你可以像下面这样简单地打电话:
$.ajax('/path/to/file').success(function (data) {
doStuff();
})