2010-06-25 6 views
0

J'utilise jQuery.En boucle sur un JSON valide et enregistrer chaque valeur dans la variable

Ceci est mon deuxième article pour clarifier ma vieille question. J'ai fait une requête Ajax en utilisant le jQuery $.ajax function à un script PHP et ce script PHP a retourné cet objet JSON et quand j'ai testé avec le texte du lien, il dit que c'est valide. et je traite cette réponse JSON avec le success fonction

Le script php est

$requete = mysql_query("SELECT * FROM annotations WHERE annot_doc_id = '$cours_selected' and annot_id_auteur = '$annot_id_auteur'"); 
while($obj = mysql_fetch_object($requete)) { 
    $arr[] = $obj; 
} 
// echo '{"exemple":'.json_encode($arr).'}'; 
echo json_encode($arr); 

Le PHP fonctionne très bien et il change dynamicly la réponse en fonction de mes besoins. Pour un i spécifique obtenu parametres cette réponse JSON

[ 
{ 
    "id_annotation": "1", 
    "annot_doc_id": "page_de_test.html", 
    "annot_id_auteur": "2", 
    "anno_startOffset": "47", 
    "annot_startContainer": "id-aaa", 
    "annot_endOffset": "88", 
    "annot_forme": "1", 
    "annot_value": "dispositif physique fait pour \n stocker ", 
    "annot_obj": "1", 
    "annot_area": "", 
    "annot_date": "vendredi 25 juin 2010 10:38:07" 
}, 
{ 
    "id_annotation": "4", 
    "annot_doc_id": "page_de_test.html", 
    "annot_id_auteur": "2", 
    "anno_startOffset": "107", 
    "annot_startContainer": "ident-77", 
    "annot_endOffset": "194", 
    "annot_forme": "1", 
    "annot_value": "crobaties avec ses doigts, mais \u00e9cartons ce cas). Avec un \n emplacement d\u2019information ", 
    "annot_obj": "1", 
    "annot_area": "", 
    "annot_date": "vendredi 25 juin 2010 10:38:33" 
} 
] 

Je veux faire une boucle et d'économiser chaque fois que le "id_annotation", "annot_doc_id", "annot_id_auteur", "anno_startOffset" .... etc dans les variables à faire quelque chose avec ces variables. Comment je peux faire ça?

PS: certains d'entre vous propsed le $.each function.

Répondre

1

Une simple boucle serait pour cela:

var objects = $.parseJSON(input); 
for (var i = 0; i < objects.length; i++) { 
    alert(objects[i].id_annotation); 
} 

Ou, si vous vouliez .each() fonction de usejQuery:

var objects = $.parseJSON(input); 
jQuery.each(objects, function() { 
    alert(this.id_annotation); 
}); 
Questions connexes