我有以下代码:
$("#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'。为什么会这样?我将如何改变这一点,以便首先获得图表?
答案 0 :(得分:6)
Async,你永远不知道哪个函数运行\先完成...
考虑异步操作,比如告诉一群人跑1英里,你知道谁先完成吗? (是的,Jon骗子,然后是Chuck Norris ......)
您可以使用a callack来运行第二个ajax:
$.post("/ajax/custom_filter/", serialized_data, function(response) {
// create a graph
...
...
$.post("/ajax/force_download/", serialized_data, function(response) {
alert('hello');
});
});
答案 1 :(得分: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');
});
答案 2 :(得分:0)
选项1是嵌套发布请求(gdoron的响应)。如果这不可行/不实用,您可以使用相互作用域的变量作为标志(在响应回调函数中更改值,然后使用setTimeout和recursion(或setInterval)继续查找“flag”变量的更改以及何时更改你看到它改变了,然后弹出下一个$ .post请求