我想根据多个ajax/json请求的结果更新页面.使用jQuery,我可以"链接"回调,就像这个非常简单的剥离示例:
$.getJSON("/values/1", function(data) {
// data = {value: 1}
var value_1 = data.value;
$.getJSON("/values/2", function(data) {
// data = {value: 42}
var value_2 = data.value;
var sum = value_1 + value_2;
$('#mynode').html(sum);
});
});
Run Code Online (Sandbox Code Playgroud)
但是,这导致请求是连续的.我更倾向于一种并行发出请求的方法,并在完成后执行页面更新.有没有办法做到这一点?
我有一个名为save()的函数,该函数收集页面上的所有输入,并对服务器执行AJAX调用以保存用户工作的状态.
当用户单击保存按钮时,当前调用save(),或执行一些需要我们在服务器上具有最新状态的其他操作(例如,从页面生成文档).
我正在增加每隔一段时间自动保存用户工作的能力.首先,我想阻止AutoSave和用户生成的保存同时运行.所以我们有以下代码(我正在削减大部分代码,这不是1:1,但应该足以让我们了解这个想法):
var isSaving=false;
var timeoutId;
var timeoutInterval=300000;
function save(showMsg)
{
//Don't save if we are already saving.
if (isSaving)
{
return;
}
isSaving=true;
//disables the autoSave timer so if we are saving via some other method
//we won't kick off the timer.
disableAutoSave();
if (showMsg) { //show a saving popup}
params=CollectParams();
PerformCallBack(params,endSave,endSaveError);
}
function endSave()
{
isSaving=false;
//hides popup if it's visible
//Turns auto saving back on so we save x milliseconds after the last save.
enableAutoSave();
} …Run Code Online (Sandbox Code Playgroud)