2011-01-20 7 views
0

J'ai deux appels ajax avec json. Le premier m'aide à obtenir la valeur globalVar. La seconde prend cette valeur, la passe à un argument dans une URL distante puis renvoie un résultat.Problème de synchronisation jQuery

var globalVar = ""; 

var firstRemoteUrl = "http://example.com/some/json"; 
     $.ajax({ 
      type: "GET", 
      url: firstRemoteUrl , 
      dataType: 'jsonp', 
      success: function (data) { 
       globalVar = data; 
      } 
     }); 


var secondRemoteUrl = "http://example.com/another/json?var = " + globalVar; 
     $.ajax({ 
      type: "GET", 
      url: secondRemoteUrl , 
      dataType: 'jsonp', 
      success: function (data) { 
       alert(data); 
      } 
     }); 

Le problème avec ce genre d'appels est que le second appel ajax ne pas attendre que le premier atteint son appel. Ainsi, parfois, globalVar est vide. Ainsi, le second appel ne se terminera pas correctement.

J'ai essayé avec async de définir ti false mais, comme indiqué dans la documentation de jquery, le type de données jsonp ignore les appels synchrones.

Existe-t-il un problème pour ce problème?

Merci,

Cordialement.

+0

Je trouve une autre workarround en ajoutant une "attente": fonction pausecomp (Millis) {var \t date = new Date(); \t var curDate = null; \t do {curDate = new Date(); } \t while (curDate-date Zakaria

Répondre

1

Vous pouvez placer le deuxième appel dans le rappel du premier. C'est un peu brouillon mais devrait faire le travail. Quelque chose comme ceci:

$.ajax({ 
type: "GET", 
url: "http://example.com/some/json", 
dataType: 'jsonp', 
success: function(data) { 
    $.ajax({ 
    type: "GET", 
    url: "http://example.com/another/json?var = " + data, 
    dataType: 'jsonp', 
    success: function(result) { 
    alert(result); 
    } 
    }); 
} 
}); 
1

Placez le deuxième appel ajax dans la fonction de rappel de succès du premier appel ajax.

var firstRemoteUrl = "http://example.com/some/json"; 
    $.ajax({ 
     type: "GET", 
     url: firstRemoteUrl , 
     dataType: 'jsonp', 
     success: function (data) { 
      globalVar = data; 
      secondRemoteUrl = "http://example.com/another/json?var = " + globalVar; 
          $.ajax({ 
            type: "GET", 
            url: secondRemoteUrl , 
             dataType: 'jsonp', 
             success: function (data) { 
                alert(data); 
               } 
             }); 
          } 
      }); 
Questions connexes