Pass in an array of Deferreds to $.when()

后端 未结 9 1246
伪装坚强ぢ
伪装坚强ぢ 2020-11-21 22:20

Here\'s an contrived example of what\'s going on: http://jsfiddle.net/adamjford/YNGcm/20/

HTML:

Click me!
&l
9条回答
  •  一向
    一向 (楼主)
    2020-11-21 22:54

    When calling multiple parallel AJAX calls, you have two options for handling the respective responses.

    1. Use Synchronous AJAX call/ one after another/ not recommended
    2. Use Promises' array and $.when which accepts promises and its callback .done gets called when all the promises are return successfully with respective responses.

    Example

    function ajaxRequest(capitalCity) {
       return $.ajax({
            url: 'https://restcountries.eu/rest/v1/capital/'+capitalCity,
            success: function(response) {
            },
            error: function(response) {
              console.log("Error")
            }
        });
    }
    $(function(){
       var capitalCities = ['Delhi', 'Beijing', 'Washington', 'Tokyo', 'London'];
       $('#capitals').text(capitalCities);
    
       function getCountryCapitals(){ //do multiple parallel ajax requests
          var promises = [];   
          for(var i=0,l=capitalCities.length; i
    
    

    Capital Cities :

    Respective Country's Native Names :

提交回复
热议问题