晚上好人 -
我注意到不同的浏览器似乎以不同的方式处理回调。
作为一个例子,Firefox似乎让$ .ajax.done({})回调中断当前的javascript指令,但Chrome将不会处理$ .ajax.done({})回调,直到所有当前指令完成。就像Chrome将呼叫发送到指令队列的末尾,Firefox将其添加到指令堆栈的顶部。
(请记住,这可能是完全错误的术语 - 我真的希望这是发布此内容的正确位置)
显示我最佳猜测的明确示例:
function load_a_bunch_of_stuff()
$.ajax({
// ajax things here - e.g. load 10,000 whatevers from a server
}).always(function() {
ajaxStatus = "done!"
});
}
function do_things_with_loaded_stuff() {
// Loops as long as the status is "running" and the User is
// willing to retry:
while (ajaxStatus === "running" &&
confirm("Waiting on ajax, try again?"));
// Do some cool stuff after the $.ajax call finishes
}
// --
// Main: (Assume do_things_with_loaded_stuff() is called before the
// load_a_bunch_of_stuff() finishes)
var ajaxStatus = "running";
load_a_bunch_of_stuff();
do_things_with_loaded_stuff();
- 我最好的猜测 -
在这个例子中 - 循环将运行,直到Firefox让.always({})将'ajaxStatus'更改为“done!” (可能在用户试图点击OK时)然后我们可以继续。
但是在Chrome中,.always({})不会触发,因为(我猜)在当前指令集完成后 后执行回调。换句话说,由于.always({})被添加到指令集的末尾(而不是在下一个插槽中),因此它被卡在循环中并且永远不会到达.always({})。
这个例子与我最近在试图在两个浏览器之间进行开发时遇到的问题类似。有谁知道这种解释是否属实?
有人能真正解释发生了什么吗?
答案 0 :(得分:0)
这不是AJAX特有的,它只是异步代码。
Firefox允许您在confirm()
,prompt()
或alert()
的模态对话框中运行异步回调。 Chrome,Safari和Internet Explorer都没有。
这可以使用setTimeout()
进行演示,但不需要$.ajax
。
function load_a_bunch_of_stuff() {
setTimeout(function() {
ajaxStatus = "done";
}, 3000);
}
function do_things_with_loaded_stuff() {
// Loops as long as the status is "running" and the User is
// willing to retry:
while (ajaxStatus === "running" &&
confirm("Waiting on ajax, try again?"));
$("div").text("Done");
}
var ajaxStatus = "running";
load_a_bunch_of_stuff();
do_things_with_loaded_stuff();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
Running
</div>
请注意,如果你取消confim()
调用,你应该期望循环在所有浏览器上无限运行,因为没有Javascript引擎应该允许异步回调来中断主流。