开发者

Issue when two server side functions are called in a jQuery function

I have a jquery that has first server function call using post and next using getJSON(). The jQuery function is given below.

$("#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);
            });

        });

Here am facing a strange issue. When executing this function, at server side, InstructionTreeView function is first hit(breakpoint) and then only the main function MoveInstruction is hit. But when I alert a text after $.post("/Instruction/MoveInstruction", { docId: DocId, instnId: rqdInstnId, action: "MoveUp" }); the functions are hit correctly as开发者_StackOverflow社区 expected. Why does this happen? Can any one help with a solution for this?


Why does this happen?

Because AJAX is asynchronous. Both requests are triggered almost at identical times and the time when they hit your server is undetermined.

If you want them to execute sequentially you need to fire the second request in the success callback of the first:

$('#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);
                }
            });
        }
    });
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜