小编典典

异步javascript事件的顺序

ajax

我有以下代码:

$("#submit_financials").live('click', function(event){
    event.preventDefault();

    // using serialize here to pass the POST variables to the django view function
    var serialized_data = $("#financials_filter_form").serialize()

    $.post("/ajax/custom_filter/", serialized_data, function(response){
        // create a graph
    });
    $.post("/ajax/force_download/", serialized_data, function(response){
        alert('hello');
    });

});

但是,当我执行此代码时,在图形 之前 会收到响应“ hello” 。为什么会这样呢?我将如何改变它以便我首先得到图形?


阅读 199

收藏
2020-07-26

共1个答案

小编典典

异步,您永远不知道哪个函数先运行\先完成…

想想异步操作,例如告诉一群人跑1英里,您知道谁会先完成吗?(是的,乔恩·斯基特,然后是查克·诺里斯…)

您可以使用Callack来运行第二个ajax:

$.post("/ajax/custom_filter/", serialized_data, function(response) {
    // create a graph
    ...
    ...

    $.post("/ajax/force_download/", serialized_data, function(response) {
        alert('hello');
    });
});​
2020-07-26