异步javascript事件的排序

Dav*_*542 2 javascript ajax jquery

我有以下代码:

$("#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');
    });

});
Run Code Online (Sandbox Code Playgroud)

但是,当我执行此代码时,我会在图表之前得到响应'hello' .为什么会这样?我将如何改变这一点,以便我首先获得图表?

gdo*_*ica 6

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

考虑异步操作,比如告诉一群人跑1英里,你知道谁先完成吗?(是的,Jon双向飞碟,然后是查克诺里斯...)

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

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

    $.post("/ajax/force_download/", serialized_data, function(response) {
        alert('hello');
    });
});?
Run Code Online (Sandbox Code Playgroud)


Sel*_*gam 5

您可以尝试使用延迟对象如果要在警报之前生成图形但希望两个调用都完成.

$.when (
   $.post("/ajax/custom_filter/", serialized_data),
   $.post("/ajax/force_download/", serialized_data)
).done(function(a1,  a2){
    /* a1 and a2 are arguments resolved for the 
    custom_filter and force_download post requests  */
   var customFilterResponse = a1[2]; 
   /* arguments are [ "success", statusText, jqXHR ] */

   //generate graph.

   alert('hello');
});
Run Code Online (Sandbox Code Playgroud)

  • 在这里我即将发布一个手动实现这个问题的答案.不知怎的,从来不知道`$ .when()`.谢谢! (2认同)