[英]How to prevent many nested functions within an (jquery) ajax call?
我正在开发一个网页,该网页通过(jquery)ajax调用检索一些数据库信息,然后处理数据并通过各种javascript函数将其显示在页面上。 我使用模块模式(下面的代码示例中为“ userapp”)来避免全局变量,并通过各种功能使用数据。
以下简化的代码有效,但前提是我将ajax调用中的所有函数(例如下面的代码中的test())都包括在内,并且我认为这将导致难看的复杂代码(也符合我的一些最佳javascript做法)在网络上阅读)。 当我尝试在ajax调用(嵌入在init()中)之外/之后调用示例函数test()时,test()无法正常工作,因为我认为ajax调用尚未完成对变量的设置(“ products []”位于例子)呢。
我的问题是:是否可以在ajax调用之外调用其他函数,如果可以,如何执行? 我查看了回调示例,但不确定是否/如何解决我的问题...
简化代码:
userapp = function(){
//userapp properties
var today = new Date();
var products = [];
var copyItems = function(source_items, target_items){
//do something
};//var copyItems
var init = function(){
$.ajax({
url: "user_admin_get.php",
data: { command: "getuserbaseinfo", val1: "", val2: "" },
success: function (msg) {
copyItems(msg.eproducts,products); //set values for 'products' used by test()
test(); //calling test() here works as the the values has been set()
},//success: function(msg)
error: function(msg) {
console.log('error result from php file:');
},//error:
dataType: "json"
});//$.ajax({
};//var init = function(){
var test = function(){
//do something
};//test()
return{init:init, test:test} //return (only) public functions and vars
}(); //userapp()
//main function document ready
$(document).ready(function(){
userapp.init();
//userapp.test(); //test() is not working here as init() has not set the requirement parameters tey
}); //$(document).ready
您想要将回调传递给init
并在此回调内调用test
。
var init = function(callback){
$.ajax({
....
success: function (msg) {
....
callback();
}
...
};
...
userapp.init(function() {
// user app is ready!
userapp.test();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.