简体   繁体   English

如何防止(jquery)ajax调用中的许多嵌套函数?

[英]How to prevent many nested functions within an (jquery) ajax call?

I'm developing a webpage that retrieves some database info via a (jquery) ajax call and then manipulates the data and displays it on the page via various javascript functions. 我正在开发一个网页,该网页通过(jquery)ajax调用检索一些数据库信息,然后处理数据并通过各种javascript函数将其显示在页面上。 I use a module pattern ('userapp' in the code example below) to avoid globals and to use the data by the various functions. 我使用模块模式(下面的代码示例中为“ userapp”)来避免全局变量,并通过各种功能使用数据。

The simplified code below works, but only if I include all the functions (such test() in the code below) within the ajax call, and I think that's going to result in ugly complex code (also in line with some best javascript practises I read on the web). 以下简化的代码有效,但前提是我将ajax调用中的所有函数(例如下面的代码中的test())都包括在内,并且我认为这将导致难看的复杂代码(也符合我的一些最佳javascript做法)在网络上阅读)。 When I tried to call the example function test() outside /after the ajax call (embedded in init()), test() does not work as I think the ajax call has not completed setting the variables ('products[]' in example) yet. 当我尝试在ajax调用(嵌入在init()中)之外/之后调用示例函数test()时,test()无法正常工作,因为我认为ajax调用尚未完成对变量的设置(“ products []”位于例子)呢。

My question: is it possible to call other functions outside the ajax call, and if so, how? 我的问题是:是否可以在ajax调用之外调用其他函数,如果可以,如何执行? I looked at callback examples but I'm not sure whether/how that would solve my problem... 我查看了回调示例,但不确定是否/如何解决我的问题...

simplified code: 简化代码:

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

You want to pass a callback to init and call test inside this callback. 您想要将回调传递给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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM