简体   繁体   中英

How to handle two ajax request?

Hello i have sequence like this

$(document).ready(function() {

    $("#ctl00_txtsearch").autocomplete({
        source: function(request, response) {
            $.ajax({
            // Here is the code of autocomplete which is requesting 
            // data and binding as autocomplete
            });
        });
 });
        var aa=bindonload();
    });

Here is the another function which i want to call on page load

function bindonload() { 
    $.get( "minicart.aspx#mydatacontent", function( data ) {
        var resourceContent = data;     
        var mini=$(resourceContent).find('div#pnlminicart');
        $('#smallcart').html(mini);
    });
    return false;
}

So , my actual problem is when page is loaded first of all

bindonload()

called and then autocomplete if textbox have some values right? But when page is loaded and suddenly i started to write into autocomplete textbox then untill bindlonload function gets executed autocomplete will not work.

I don't have idea how to handle it i have used async:true but its not working i don't want to wait for second process

Thanks in advance....

Well..what i guess..should be..you loaddata() should not be taking too much of time to load.

If there is any way to optimize , look of that.

If you ajax request has a dependency on the other, then you can not make it parallel

If you really intend to make parallel ajax requests, you have to make use of the following:

$.when($.ajax("URL1"), $.ajax("URL2"))
  .then(myFunc, myFailure); 

Hope it helps..

Note : The Ajax calls should not be dependent

Updated:

    $.when( $.ajax( "/page1.php" ), $.ajax( "/page2.php" ) ).done(function( a1, a2 )
 { 

     // a1 and a2 are arguments resolved for the page1 and page2 ajax requests, respectively.  
    // Each argument is an array with the following structure: 
    [ data, statusText, jqXHR ]  
    var data = a1[ 0 ] + a2[ 0 ]; // a1[ 0 ] = "Whip", a2[ 0 ] = " It"  if ( /Whip It/.test( data ) ) {    alert( "We got what we came for!" );  
}}); 

In the above example , you can see two ajax requests executes parallel

After the two requests are done, ie on sucess of two functions , the add operation is being performed

Similarly , you can replace $.ajax("/page1.php") with your loaddata() and then

$.ajax("page2.php") with your Auto Complete request .

Both of them will execute Parallely

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM