Consider a scenarios where you have multiple source of data and that needs to be consolidated in the UI and presented to the users. There can be different ways to implement this. One option can be using AJAX approach. JQuery provides a way to initiate parallel AJAX calls. In this blog i will be showing a sample code to achieve same.
Using Jquery provided "$.when" function, which provides a way of executing asynchronous events. $.when takes asynchronous ajax events as a parameter, and the output of these AJAX events will return in ".then" in the same order.
$.when(ajax1, ajax2,....).then(resp1,resp2,....);
Following is the sample code to make parallel ajax call.
var url1="http://localhost:8080/url1"; var url2="http://localhost:8080/url2"; var param="s=abcd"; $.when( $.ajax({timeout:10000,error:function(){handleErrorScenario();},type: "get", url:url1, async : true, data:param}), $.ajax({timeout:10000,error:function(){handleErrorScenario();},type: "get",url:url2, cache: true,async : true, data:param}) ) .then(function(url1Resp, url2Resp){ if(!url1Resp || !url2Resp){ handleErrorScenario();//define this function. }else{ handleSuccessScenario(url1Resp, url2Resp); //define this function. } }In the above sample there are two AJAX function which are passed as parameter. url1Resp and url2Resp will hold the output from the call. Code inside ".then" will be only executed when all the deferred AJAX response comes back. Some of the function needs to be defined in the your code. I am using them as dummy reference.
No comments:
Post a Comment