【发布时间】:2011-07-19 23:42:48
【问题描述】:
我想要异步运行以下代码,但日志显示它们正在同步运行。
$(".widget").each(function() {
// snip - url, def, and tempParams defined here
$.ajax({
url: url,
dataType: "jsonp",
type: "POST",
data: {params: tempParams},
success: function(data) {
var st = new Date().getTime();
console.error("Start " + def.name + " @" + st);
doSomething(data);
var et = new Date().getTime();
console.error("End " + def.name + " @" + et);
console.error("Duration " + def.name + " " + (et-st) + " ms.");
}
});
控制台输出清楚地显示成功函数按顺序执行,而不是异步执行:
Start f1 @1300738891705
End f1 @1300738891744
Duration f1 39 ms.
Start f2 @1300738892746
End f2 @1300738893280
Duration f2 534 ms.
Start f3 @1300738893282
End f3 @1300738893303
Duration f3 21 ms.
Start f4 @1300738893305
End f4 @1300738893306
Duration f4 1 ms.
Start f5 @1300738893484
End f5 @1300738895609
Duration f5 2125 ms.
想法?我觉得这一定是我忽略的显而易见的事情。
【问题讨论】:
标签: jquery ajax asynchronous