强制JavaScript以所需顺序执行

I have an issue when trying to get Javascript to execute functions in my desired order. I'm trying to get a jQuery modal form to load information based on a certain selection. I have two SELECT boxes that need to be loaded, but the contents of the second SELECT box depend entirely on the selected value of the first SELECT box.

I made the following functions to request the information I need:

function get_Subjects(varID, callback){
    $.post("../vars/get_SID.php", { vid : varID },  
        function(result){
            getInfo('tbsubjectdiv', '../vars/findSubjectlist.php?sid='+result);
        });
    callback();
}

function get_Selectedfields(varID, callback){
    $.post("../vars/requestTblock.php", { vid : varID },  
        function(result){
            populateForm('tbWiz', result);
            document.form_tbWiz.varname.disabled = true;
            $('.trSearch').hide();
            $('.trValueset').hide();
        });
    callback();
}

function get_TextblockType(varID, callback){
    $.post("../vars/requestVtype.php", { vid : varID },  
        function(result){
            if(result == 0){ //Opzoeken
                $('.trSearch').show();
            }else if(result == 1){ //Datum vergelijken
                $('.trSearch').show();
                $('.trValueset').show();
            }else if(result == 2){ //Percentage
                //
            }
        });
    callback();
}
  1. The first function checks the MySQL database for the selected value of the FIRST SELECT field, and loads the results into the second SELECT field.

  2. The second function requests the rest of the rest of the form data, and populates the form using populateForm(). It also hides certain parts of my form in preparation for function three.

  3. The third function basically requests which parts of the form have to be displayed, because that's not always the same.

The whole idea behind this is that I want to use populateForm() to populate all of the form fields. In order for populateForm() to properly set the selected SELECT option, the particular SELECT field must first contain the OPTION it needs to select. Makes sense. I try to make sure of this with my first function, which will load all of the OPTIONs. THEN I try to use the get_Selectedfields() to populate all the proper values. This is not what happens though. No matter what I try to do, getInfo() in the first function is ALWAYS being called LAST. This makes it impossible for populateForm() to select the proper option, which is driving me mad.

I'm trying to "force" the execution-order by doing this:

function getTextblock(var_ID){
get_Subjects(var_ID, function() {
    get_Selectedfields(var_ID, function() {
        get_Textblocktype(var_ID, function() {
            // Done
        });
    });
}); 

}

When I realised it still did not work the way I wanted, I decided to use Chrome's Developer Tools to check the order in which everything is executed. It all works as expected, but at the very end it jumps straight back to getInfo(), which is part of the FIRST function I called. I'm absolutely clueless as to why getInfo() gets executed last. If this just gets executed at the very beginning, where I want it to execute, it would all work fine.

5个回答



你必须在post请求的回调函数中调用回调:</ p>

  function get_Subjects(varID,callback){
$ .post(“../ vars / get_SID.php”,{vid:varID},
function(result){
getInfo('tbsubjectdiv','.. /vars/findSubjectlist.php?sid='+result);
callback();
});

}

函数get_Selectedfields(varID,callback){
$ .post(“.. /vars/requestTblock.php“,{vid:varID},
function(result){
populateForm('tbWiz',result);
document.form_tbWiz.varname.disabled = true;
$('。 trSearch')。hide();
$('。trValueset')。hide();
callback();
});

}

函数get_TextblockType(varID,callback){\ n $ .post(“../ vars / requestVtype.php”,{vid:varID},
function(result){
if(result == 0){// Opzoeken
$('。trSearch' ).show();
} else if(result == 1){// D atum vergelijken
$('。trSearch')。show();
$('。trValueset')。show();
} else if(result == 2){// Percentage
// \ n}
callback();
});

}
</ code> </ pre>
</ div>

展开原文

原文

You have to call the callback in the callback function of the post request:

function get_Subjects(varID, callback){
    $.post("../vars/get_SID.php", { vid : varID },  
        function(result){
            getInfo('tbsubjectdiv', '../vars/findSubjectlist.php?sid='+result);      
            callback();
        });

}

function get_Selectedfields(varID, callback){
    $.post("../vars/requestTblock.php", { vid : varID },  
        function(result){
            populateForm('tbWiz', result);
            document.form_tbWiz.varname.disabled = true;
            $('.trSearch').hide();
            $('.trValueset').hide();
            callback();
        });

}

function get_TextblockType(varID, callback){
    $.post("../vars/requestVtype.php", { vid : varID },  
        function(result){
            if(result == 0){ //Opzoeken
                $('.trSearch').show();
            }else if(result == 1){ //Datum vergelijken
                $('.trSearch').show();
                $('.trValueset').show();
            }else if(result == 2){ //Percentage
                //
            }
            callback();
        });

}

dow56114
dow56114 想出来,谢谢你的帮助! 结束了将“回调”放入getInfo()参数行,并确保在获得getXMLHTTP结果后立即调用回调。
接近 9 年之前 回复
dongpu4141
dongpu4141 是的,getInfo(div,url)使用getXMLHTTP从url参数中的url获取内容并将其放入提供的div中。 我认为我的思维过程目前要复杂得多。 我究竟如何在getInfo()中实现回调函数? 我不认为简单地将“回调”干扰到参数行就足够了吧? 我想这表明我只用了2天的JavaScript。
接近 9 年之前 回复
dongyanju1094
dongyanju1094 是的,我没有意识到,getInfo看起来像是在发出ajax请求。 getInfo()需要采用回调函数。 然后你可以这样做:getInfo('tbsubjectdiv','.. / vars / findSubjectlist.php?sid ='+ result,callback);
接近 9 年之前 回复
douchenzhan3050
douchenzhan3050 工作,但根本不可靠。 平均而言,它的工作时间为10%。 我想它仍然不会等待getInfo()在继续之前完成,这可能是由异步因素引起的。
接近 9 年之前 回复



Wesley,</ p>

javascript将始终按预定义的顺序执行。 如果你在代码中间放了一堆“alerts()”,你可以尝试一下。</ p>

回调</ strong>并非如此,因为 它们将被移动到javascript上执行堆栈的底部,我们无法确定顺序,因为它们是由AJAX返回调用的,根据定义,它是异步的。 </ p>

即使你的ajax在一毫秒内执行,在你的脚本块中的所有方法都完成之后才会执行回调。</ p>

你有, 实际上有三个选项:</ p>


  1. 链接回调中的所有方法序列。 请不要回拨!! </ strong>它应该是你,但是那个会调用它们的“系统”。</ li>
    </ ol>

     
    //首先需要的数据
    函数myStartPoint(){
    $ .post(url,function(result){
    //使用此结果执行您需要的操作(这是您的回调,但是匿名)

    //然后,调用下一步
    secondPoint();
    });
    }

    函数secondPoint(){
    $ .post(url,function(result){
    // // 再次,回调是匿名的...你几乎不需要声明一个名为callback的东西
    //链你需要多少个点
    nextPoint();
    }
    }
    </ pre>


    1. “强制”ajax与 async:false </ strong>选项同步。这可能会导致性能问题。</ li>
    2. 最丑陋的是 使用该死的 setTimeout </ strong>,这是非常非常错误的,但是会在你的情况下工作,因为,即使在那些回调之后,setTimeout也会将方法放在执行堆栈的底部 预计会很快。 说真的,我只是提出这个选项,因为最终有人会这么说......不要走这条路。</ li>
      </ ol>
      </ div>

展开原文

原文

Wesley,

The javascript will execute always on the predefined order. If you put a bunch of "alerts()" in the middle of your code, you can taste that.

But this is not true for callbacks, because they will be moved to the bottom of execution stack on javascript where we can't determine the order, since they are called by a AJAX return which by definition is asynchronous.

Even though your ajax executes in a millisecond, the callback will not be executed until all methods in your script block have finished.

You have, actually three options:

  1. Chain all the methods sequence in callbacks. Please, don't call a callback!! It inst supposed to be you, but the "system" that will call those.
  // The data you need first
  function myStartPoint() {
    $.post(url, function(result) {
       // do what you need with this result (this is your callback, but anonymous)
       // then, call the next step
       secondPoint();
    });
  }

  function secondPoint() {
    $.post(url, function(result) {
      // again, the callback is anonymous... your hardly need to declare something named callback
      // chain how many points as you need
      nextPoint();
    }
  }
  1. "Force" the ajax to be synchronous with async:false option. This can cause performance issues.
  2. The ugliest of all is to use the damned setTimeout which is very, very wrong, but will work in your case because, the setTimeout will put the method on the bottom of execution stack even after those callbacks which are expected to be fast. Seriously, I just put this option because eventually someone would say it... Do not take this path.



您正在使用ajax。 第一个是异步的。 如果你从函数(结果)块调用函数,那么它们将按顺序发生。</ p>

或者(这不是一个好主意,但你可以这样做)使用$。 ajax()对象并将async设置为false。</ p>
</ div>

展开原文

原文

You're using ajax. The first a is for asynchronous. If you called the functions from the function(result) blocks then they would occur in order.

Alternatively (and this isn't a great idea but you can do it) use the $.ajax() object and set async to false.



由于您不知道ajax请求实际需要多长时间,因此您只能在ajax响应中链接事件:</ p>

 函数getTextblock(var_ID){
$ .post(YOUR_TARGET,YOUR_DATA,函数(结果){
YOUR_CODE
//链接此处,调用新函数或子ajax请求
});
}
</ code> </ pre>
</ div>

展开原文

原文

As you don't know how long long an ajax request will actually take, you can only chain events within the ajax response:

function getTextblock(var_ID){
    $.post(YOUR_TARGET, YOUR_DATA, function(result){
        YOUR_CODE
        // CHAIN HERE, call new function or sub ajax request
    });
}

doucheyi1347
doucheyi1347 我想尝试这个,但似乎我必须这样做,以便getInfo()允许我根据结果执行某些事情,对吧?
接近 9 年之前 回复



POST正在您的函数中异步处理,因此您的“回调”实际上只是在您的初始调用后几乎立即执行,而 发布后,正在执行 $ .post </ code>的回调。 这有助于你解决问题吗? 您可能需要在 $。post(“../ vars / get_SID.php”,{vid:varID} ... </ code> </ p>的回调中启动剩余的过程。

$ .post </ code>是 $。ajax </ code>的简写,因此您可以在jQuery文档中读取更多内容,但我不建议切换到同步请求。如果你必须在下一个请求完成之前完成一个请求然后开始 回调的下一步是要走的路。</ p>
</ div>

展开原文

原文

The POST is being handled asynchronously in your functions so your "callback" is really just being executed almost immediately after your initial call, whereas the callback of $.post is being executed after the post has occurred. Does that help you sort things out? You will probably need to kick off the rest of the process in the callback of $.post("../vars/get_SID.php", { vid : varID }...

$.post is shorthand for $.ajax so you can read up a bit more in the jQuery docs, but I would not suggest switching to synchronous requests. If you absolutely must have one request finished before the next can execute then kicking off that next step from the callback is the way to go.

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问