2010-03-09 2 views
2

Pourquoi ce code renvoie-t-il toujours 0?Pousser vers Javascript Tableau depuis la requête JSON Jquery

 var possibleMatches = new Array(); 
    $.getJSON('getInformation.php', function(data) { 
    $.each(data, function(i){ 
    possibleMatches.push(data[i]); 
    }) 
    }); 
    alert(possibleMatches.length); 

Bien que je puisse déplacer ou ajouter "alert (possibleMatches.length);" à l'intérieur du $ .each et il produira le bon nombre d'éléments. Je suis juste curieux de savoir pourquoi les valeurs ne vont pas dans le tableau comme je m'y attendais. Je suis sûr que c'est une variable locale par rapport à la variable globale, mais je ne sais pas pourquoi. Fondamentalement, ce que nous essayons de faire est de remplir le tableau possibleMatches avec les résultats de données.

merci!

Répondre

6

Asynchronicité. La ligne alert(possibleMatches.length); s'exécute avant que le rappel de succès pour $.getJSON() s'exécute. Donc, pour que votre alerte soit précise, déplacez-la.

var possibleMatches = new Array(); 
$.getJSON('getInformation.php', function(data) { 
    $.each(data, function(i){ 
    possibleMatches.push(data[i]); 
    }) 

    // To here 
    alert(possibleMatches.length); 
}); 
// From here 

Rappelez-vous, le premier Un en AJAX signifie "Asynchronous"

+0

@Peter Bailey - Doh! Comment ai-je oublié cette petite partie (mais très importante)! Cela prend tout son sens! Merci! –

+0

+1 - Je ne croyais pas que Asynchronicity était un mot :) –

2

$.getJSON effectue un appel asynchrone, dont le rappel est exécutée à la fin du xmlhttprequest utilisé:

var possibleMatches = new Array(); 
$.getJSON('getInformation.php', function(data) { // <-- this will run later 
    $.each(data, function(i){ 
     possibleMatches.push(data[i]); 
    }) 
}); 
alert(possibleMatches.length); // this will call immediately 
1

Le La requête jetJSON est asynchrone, elle s'est terminée après l'exécution de votre alerte. Si vous voulez une alerte accruate, il devrait être dans votre rappel pour getJSON comme ceci:

$.getJSON('getInformation.php', function(data) { 
    $.each(data, function(i){ 
    possibleMatches.push(data[i]); 
    }); 
    alert(possibleMatches.length); 
    }); 
Questions connexes