2010-08-19 14 views
0

J'ai effectué cette fonction pour obtenir les résultats d'une requête directement dans une structure de données utile. Le problème est le suivant: dans le premier appel console.log(), à l'intérieur de la fonction callback, la variable stored_data contient les résultats exacts, dans le second appel de console.log() la variable stored_data n'a pas l'air d'être initialisée. Suggestions?? Ci-dessous le code:Visibilité variable dans les fonctions de rappel

function dojo_query_mysql(query_string) { 
     //The parameters to pass to xhrPost, the message, and the url to send it to 
     //Also, how to handle the return and callbacks. 
     var stored_data; 
    var raw_data = new Object; 
     var xhrArgs = { 
     url: "query.php", 
     postData: query_string, 
     handleAs: "text", 
     load: function(data) { 
      raw_data = dojo.fromJson(data); 
      stored_data = new dojo.data.ItemFileReadStore({data: raw_data}); 
    console.log(stored_data); 
     }, 
     error: function(error) { 
      //We'll 404 in the demo, but that's okay. We don't have a 'postIt' service on the 
      //docs server. 
      //stored_data = error; 
     } 
     } 
     //Call the asynchronous xhrPost 
     var deferred = dojo.xhrPost(xhrArgs); 
    console.log(stored_data); 
     return stored_data; 
    } 

Répondre

0

Je viens de me rappeler que la fonction n'attend pas la fin de l'exécution de rappel, pour attendre la fin de rappel faire juste un peu de changement au code:

var xhrArgs = { 
     url: "query.php", 
sync: true, // THIS IS FORCE THE SYNCRONIZATION BETWEEN THE CALLBACK AND THE CODE 
     postData: query_string, 
     handleAs: "text", 
     load: function(data) { 
      raw_data = dojo.fromJson(data); 
      stored_data = new dojo.data.ItemFileReadStore({data: raw_data}); 
    console.log(stored_data); 
     }, 
     error: function(error) { 
      //We'll 404 in the demo, but that's okay. We don't have a 'postIt' service on the 
      //docs server. 
      //stored_data = error; 
     } 
     } 
+0

Vous ne devriez ** jamais ** utiliser 'sync: true' sauf si c'est absolument nécessaire. Il bat une grande partie de l'objectif de XHR, et prend le premier A à partir d'AJAX. Idéalement, tout code basé sur le résultat du XHR devrait être dans le rappel 'load' ou ajouté à un rappel ultérieur en utilisant' then' (ou 'addCallback' dans Dojo <1.5). –