在jQuery函数中调用两个服务器端函数时出现问题
我有一个jquery,第一个服务器函数调用使用post,下一个使用getJSON。jQuery函数如下所示在jQuery函数中调用两个服务器端函数时出现问题,jquery,asp.net-mvc-2,Jquery,Asp.net Mvc 2,我有一个jquery,第一个服务器函数调用使用post,下一个使用getJSON。jQuery函数如下所示 $("#move_up").live("click", function(e) { var rqdInstnId = GetRequiredId(); //alert(rqdInstnId); $.post("/Instruction/MoveInstruction", { docId: DocId, instnId:
$("#move_up").live("click", function(e) {
var rqdInstnId = GetRequiredId();
//alert(rqdInstnId);
$.post("/Instruction/MoveInstruction", { docId: DocId, instnId: rqdInstnId, action: "MoveUp" });
//alert("moved");
//$.ajaxSetup({ cache: false });
$.getJSON(
'/Instruction/InstructionTreeView',
{ docId: DocId, instnId: InstnId },
function(data) {
//alert(data);
$.ajaxSetup({ cache: false });
$('.initialTree').html(data);
ExpandTree();
PersistLayout();
PersistSelection(rqdInstnId);
});
});
我面临着一个奇怪的问题。在服务器端执行此函数时,首先命中InstructionTreeView函数的断点,然后只命中主函数MoveInstruction。但是,当我在$.post/Instruction/MoveInstruction之后警告文本时,{docId:docId,instnId:rqdInstnId,action:MoveUp};
函数按预期正确命中。为什么会发生这种情况?有人能帮忙解决这个问题吗
为什么会发生这种情况
因为AJAX是异步的。两个请求几乎在相同的时间触发,它们到达服务器的时间尚未确定
如果希望它们按顺序执行,则需要在第一个成功回调中触发第二个请求:
$('#move_up').live('click', function(e) {
var rqdInstnId = GetRequiredId();
$.post(
'/Instruction/MoveInstruction',
{ docId: DocId, instnId: rqdInstnId, action: "MoveUp" },
function(result) {
// The first POST request finished successfully
// => now trigger the second
$.getJSON(
'/Instruction/InstructionTreeView',
{ docId: DocId, instnId: InstnId },
function(data) {
$.ajaxSetup({ cache: false });
$('.initialTree').html(data);
ExpandTree();
PersistLayout();
PersistSelection(rqdInstnId);
}
});
}
});
});