Ordering of asynchronous javascript events

前端 未结 3 1425
没有蜡笔的小新
没有蜡笔的小新 2021-01-22 11:47

I have the following code:

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

    // using serialize here to pass the POST v         


        
相关标签:
3条回答
  • 2021-01-22 12:31

    option 1 is to nest the post requests (gdoron's response). If this is not possible/practical, you can use a mutually scoped variable as a flag (change value in the response callback functions and then use setTimeout and recursion (or setInterval) to keep looking for a change in your "flag" variable and when you see it change, then pop the next $.post request

    0 讨论(0)
  • 2021-01-22 12:36

    You can try using deferred objects If you want to generate graph before alert but want both calls to be completed.

    $.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');
    });
    
    0 讨论(0)
  • 2021-01-22 12:38

    Async, you can never know which function runs\ finish first...

    Think on async operations like telling a group of people to run 1 mile, do you know who will finish first? (Yes, Jon skeet, then Chuck Norris...)

    You can use the a callack to run the second ajax:

    $.post("/ajax/custom_filter/", serialized_data, function(response) {
        // create a graph
        ...
        ...
    
        $.post("/ajax/force_download/", serialized_data, function(response) {
            alert('hello');
        });
    });​
    
    0 讨论(0)
提交回复
热议问题