开发者

how to deal with async calls in Ajax 4.0(using jquery?)

in my code i have done something like this.

 $.get('/Home/Module/Submit',
                { moduleName: ModName,
                    moduleParameters: moduleParameters
                },

   function(result) {


       $("#" + target).html(result);

   });

when i put alert in the function(result) {..} it shows html perfectly(both in alert and at the 'target'-on the开发者_C百科 .aspx page) BUT when i remove the alert.. on the page the 'html' don't appear or appear randomly (this method is called multiple times)

i think that the 'result' comes to function asynchronously thats why it is not bind with the respective 'div' however in the last iteration it gets bind every time.

can we make process stop until data gets bind? or is there any functionality (like alert) which can make data bind.. without disturbing UI (unlike alert)?


Your callback function makes use of target which is defined in an outside scope, possibly global. You say you're doing this call several times, and that the last iteration works every time, so I'm guessing that target is actually changed by some outside influence? In that case, it may very well be that the value of target is not what you think it is, at the time of execution. You can create a new closure in which target will be sure not to change:

$.get('/Home/Module/Submit', { data }, (function(t) {
    return function(result) {
        $("#" + t).html(result);
    }
})(target));

What we're doing here is to create a new anonymous function that returns the callback function you want to use. You can think of it as a factory function. This function is being called immediately, just before the call to get, as it has to be evaluated to work out the third parameter to pass to get. We call this function, passing target, so the value of target will be the value it has by the time of the AJAX call, not, like before, by the time of the AJAX response. A new closure will be created for each iteration, where its respective t parameter will correspond to the value of target at the time of its creation.

You do not want to come up with something that will keep the JavaScript from executing until a certain other piece of code has been executed.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜