IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Symfony PHP Discussion :

Parser un tableau en JSON [2.x]


Sujet :

Symfony PHP

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre confirmé
    Profil pro
    Inscrit en
    Octobre 2006
    Messages
    162
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Octobre 2006
    Messages : 162
    Par défaut Parser un tableau en JSON
    Bonjour,

    Je suis en train de faire de l'Ajax et je n'arrive pas à parser un tableau en JSON. On peut considérer ce topic un peut comme la suite du topic "Utiliser Ajax avec Symfony2" car je reprends un peu les même codes par contre, c'est un autre soucis.

    Voilà les codes:

    AjaxController.php

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
     
    <?php
     
    namespace Ajax\AppliBundle\Controller;
     
    use Symfony\Bundle\FrameworkBundle\Controller\Controller;
    use Symfony\Component\HttpFoundation\Response;
    use Ajax\AppliBundle\Entity\Coffre;
     
    class AjaxController extends Controller
    {
        public function nombreObjetsRequeteAction()
         {
            //On récupère l'entityManager
            $em = $this->getDoctrine()->getManager();
     
            //On récupère le repository de Coffre
            $repositoryCoffre = $em->getRepository('AjaxAppliBundle:Coffre');
     
            //On récupère le coffre que l'on souhaite (1er enregistrement de la table)
            $listeCoffres = $repositoryCoffre->findAll();
     
            $tableauCoffre = array();
            $item = array();
     
            foreach($listeCoffres as $coffre)
            {
                $item['identifiant'] = $coffre->getId();
                $item['nombre_objets'] = $coffre->getNombreObjets();
                $item['couleur'] = $coffre->getCouleur();
            }
     
            //On met item comme premier élément de $tableauCoffre
            $tableauCoffre[0] = $item;
     
            //On encode en JSON
            $response = new Response(json_encode($tableauCoffre));
            $response->headers->set('Content-Type', 'application/json');
     
            return $response;
        }
     
        public function nombreObjetsVueAction()
        {        
            return $this->render('AjaxAppliBundle:Principale:affichage-coffre.html.twig');
        }
    }
    affichage-coffre.html.twig

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    {% extends "::base.html.twig" %}
    
    {% block body %}
    {{ parent() }}
    
    <h2>Test de la méthode AJAX</h2>
     
    Le coffre contient <div id="nbobjets"></div> objets actuellement.
    {% endblock %}
     
    {% block javascripts %}
    
    {{ parent() }}
    
    <script type="text/javascript">
    $(document).ready(function()
    { 
        var tableau_coffre = new Array();
        
        function valueOnline()
        {
            $.ajax(
            {
                type: 'GET',
                url: "{{ url('ajax_appli_coffre_requete') }}",
                success: function (data)
                {
                    tableau_coffre = jQuery.parseJSON(data);
    
                    identifiant_coffre = tableau_coffre[0].identifiant;
    
                    $("#nbobjets").html(identifiant_coffre);
                }
            });
        }
    
        //Fonctionne
        setInterval(function() { valueOnline(); }, 1000);    
    });
    </script>
    {% endblock %}
    routing.yml

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
     
    ajax_appli_coffre_requete: 
        path:     /coffre-requete
        defaults: { _controller: AjaxAppliBundle:Ajax:nombreObjetsRequete }
     
    ajax_appli_coffre_vue: 
        path:     /coffre-vue
        defaults: { _controller: AjaxAppliBundle:Ajax:nombreObjetsVue }
    Du coup, j'ai fait un tableau avec un élément que j'aimerais parser avec la fonction jQuery.parseJSON mais je n'ai pas le résultat escompté.

    Je ne vois pas pourquoi la valeur de tableau_coffre[0]['identifiant'] ne s'affiche pas dans le twig.

    Voilà à quoi ressemble le tableau avec un var_dump:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
     
    array (size=1)
      0 => 
        array (size=3)
          'identifiant' => int 4
          'nombre_objets' => string '94' (length=2)
          'couleur' => string 'vert' (length=4)
    Pouvez vous m'orienter s'il vous plaît?

    Je vous remercie par avance,

  2. #2
    Membre extrêmement actif
    Avatar de dukoid
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Novembre 2012
    Messages
    2 100
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Développeur informatique

    Informations forums :
    Inscription : Novembre 2012
    Messages : 2 100
    Par défaut
    héééééééééééééééééé mister henryyyyyyyyyyyyyyyyyyyyyyyyy


    bon, le dump du tableau tu le fais ou dans la vue ? (parceque cela me semble louche )

  3. #3
    Membre confirmé
    Profil pro
    Inscrit en
    Octobre 2006
    Messages
    162
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Octobre 2006
    Messages : 162
    Par défaut
    Salut,

    Oui, pour le dump j'avais recopié une partie du code de nombreObjetsRequeteAction de AjaxController.php dans l'action nombreObjetsVueAction du même controller et j'avais également commenter le JavaScript du twig.

    C'est surtout pour bien mettre en évidence à quoi ressemble le tableau. Toutefois, j'ai modifié mon tableau car je préfère que la clé soit un string et je prend en compte les 4 coffres qui sont dans ma BDD;

    Également, l'objet Coffre a maintenant un attribut en plus qui est couleur.

    Voilà, le code pour le nouveau var_dump du coup:

    AjaxController.php

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    <?php
    
    namespace AjaxAppliBundle\Controller;
    
    use Symfony\Bundle\FrameworkBundle\Controller\Controller;
    use Symfony\Component\HttpFoundation\Response;
    use AjaxAppliBundle\Entity\Coffre;
    
    class AjaxController extends Controller
    {
    	public function nombreObjetsRequeteAction()
     	{
    		//On récupère l'entityManager
    		$em = $this->getDoctrine()->getManager();
     
    		//On récupère le repository de Coffre
    		$repositoryCoffre = $em->getRepository('AjaxAppliBundle:Coffre');
     
    		//On récupère le coffre que l'on souhaite (1er enregistrement de la table)
    		$listeCoffres = $repositoryCoffre->findAll();
    
    		//On initialise les tableaux et la variable $i
    		$tableauCoffre = array();
    		$item = array();
    		$i = 0;
    		
    		foreach($listeCoffres as $coffre)
    		{
    			$item['identifiant'] = $coffre->getId();
    			$item['nombre_objets'] = $coffre->getNombreObjets();
    			$item['couleur'] = $coffre->getCouleur();
    			
    			$i = $i + 1;
    			
    			//On affecte un élément $item à $tableauCoffre
    			$tableauCoffre["element".$i] = $item;
    		}
    
    		//On encode en JSON
    		$response = new Response(json_encode($tableauCoffre));
    		$response->headers->set('Content-Type', 'application/json');
     
    		return $response;
        }
        
        public function nombreObjetsVueAction()
        {    	
        	//On récupère l'entityManager
        	$em = $this->getDoctrine()->getManager();
        	
        	//On récupère le repository de Coffre
        	$repositoryCoffre = $em->getRepository('AjaxAppliBundle:Coffre');
        	
        	//On récupère le coffre que l'on souhaite (1er enregistrement de la table)
        	$listeCoffres = $repositoryCoffre->findAll();
        	
        	//On initialise les tableaux et la variable $i
        	$tableauCoffre = array();
        	$item = array();
        	$i = 0;
    		
    		foreach($listeCoffres as $coffre)
    		{
    			$item['identifiant'] = $coffre->getId();
    			$item['nombre_objets'] = $coffre->getNombreObjets();
    			$item['couleur'] = $coffre->getCouleur();
    			
    			$i = $i + 1;
    			
    			//On affecte un élément $item à $tableauCoffre
    			$tableauCoffre["element".$i] = $item;
    		}
        	
        	return new Response(var_dump($tableauCoffre));
        	
        	//return $this->render('AjaxAppliBundle:Principale:affichage-coffre.html.twig');
        }
    }
    affichage-coffre.html.twig (j'avais commenté le JavaScript)

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    {% extends "::base.html.twig" %}
    
    {% block body %}
    {{ parent() }}
    
    <h2>Test de la méthode AJAX</h2>
     
    Le coffre contient <div id="nbobjets"></div> objets actuellement.
    {% endblock %}
     
    {% block javascripts %}
    
    {{ parent() }}
    
    {# <script type="text/javascript">#}
    {# $(document).ready(function()#}
    {# { #}
    {# 	var nombre_objet = 0;#}
    	
    {# 	function valueOnline()#}
    {# 	{#}
    {# 		$.ajax(#}
    {# 		{#}
    {# 			type: 'GET',#}
    {# 			data: nombre_objet,#}
    {# 			url: "{{ url('ajax_appli_coffre_requete') }}",#}
    {# 			success: function (data)#}
    {# 			{#}
    {# 				tableau_coffre = jQuery.parseJSON(data);#}
    
    {# 				$("#nbobjets").html(tableau_coffre.element1.identifiant);#}
    {# 			}#}
    {# 		});#}
    {# 	}#}
    
    {# 	//Fonctionne#}
    {# 	setInterval(function() { valueOnline(); }, 1000);	#}
    {# });#}
    {# </script>#}
    {% endblock %}
    Coffre.php

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
     
    <?php
     
    namespace AjaxAppliBundle\Entity;
     
    use Doctrine\ORM\Mapping as ORM;
     
    /**
     * Coffre
     *
     * @ORM\Table()
     * @ORM\Entity(repositoryClass="AjaxAppliBundle\Entity\CoffreRepository")
     */
    class Coffre
    {
        /**
         * @var integer
         *
         * @ORM\Column(name="id", type="integer")
         * @ORM\Id
         * @ORM\GeneratedValue(strategy="AUTO")
         */
        private $id;
     
        /**
         * @var string
         *
         * @ORM\Column(name="nombre_objets", type="string", length=255)
         */
        private $nombreObjets;
     
        /**
         * @var string
         *
         * @ORM\Column(name="couleur", type="string", length=255)
         */
        private $couleur;
     
        /**
         * Get id
         *
         * @return integer 
         */
        public function getId()
        {
            return $this->id;
        }
     
        /**
         * Set nombreObjets
         *
         * @param string $nombreObjets
         * @return Coffre
         */
        public function setNombreObjets($nombreObjets)
        {
            $this->nombreObjets = $nombreObjets;
     
            return $this;
        }
     
        /**
         * Get nombreObjets
         *
         * @return string 
         */
        public function getNombreObjets()
        {
            return $this->nombreObjets;
        }
     
        /**
         * Set couleur
         *
         * @param string $couleur
         * @return Coffre
         */
        public function setCouleur($couleur)
        {
            $this->couleur = $couleur;
     
            return $this;
        }
     
        /**
         * Get couleur
         *
         * @return string 
         */
        public function getCouleur()
        {
            return $this->couleur;
        }
    }
    Ce que me donne le var_dump:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
     
    array (size=4)
      'element1' => 
        array (size=3)
          'identifiant' => int 1
          'nombre_objets' => string '78' (length=2)
          'couleur' => string 'rouge' (length=5)
      'element2' => 
        array (size=3)
          'identifiant' => int 2
          'nombre_objets' => string '79' (length=2)
          'couleur' => string 'vert' (length=4)
      'element3' => 
        array (size=3)
          'identifiant' => int 3
          'nombre_objets' => string '49' (length=2)
          'couleur' => string 'violet' (length=6)
      'element4' => 
        array (size=3)
          'identifiant' => int 4
          'nombre_objets' => string '45' (length=2)
          'couleur' => string 'orange' (length=6)



    Voilà, le nouveau code que je teste et qui ne fonctionne pas.

    En fait, ce que je souhaite c'est récupérer, la valeur $tableauCoffre['element']['identificant'] une fois le tableau parsé avec la fonction jQuery.parseJSON.

    AjaxController.php

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    <?php
    
    namespace AjaxAppliBundle\Controller;
    
    use Symfony\Bundle\FrameworkBundle\Controller\Controller;
    use Symfony\Component\HttpFoundation\Response;
    use AjaxAppliBundle\Entity\Coffre;
    
    class AjaxController extends Controller
    {
    	public function nombreObjetsRequeteAction()
     	{
    		//On récupère l'entityManager
    		$em = $this->getDoctrine()->getManager();
     
    		//On récupère le repository de Coffre
    		$repositoryCoffre = $em->getRepository('AjaxAppliBundle:Coffre');
     
    		//On récupère le coffre que l'on souhaite (1er enregistrement de la table)
    		$listeCoffres = $repositoryCoffre->findAll();
    
    		//On initialise les tableaux et la variable $i
    		$tableauCoffre = array();
    		$item = array();
    		$i = 0;
    		
    		foreach($listeCoffres as $coffre)
    		{
    			$item['identifiant'] = $coffre->getId();
    			$item['nombre_objets'] = $coffre->getNombreObjets();
    			$item['couleur'] = $coffre->getCouleur();
    			
    			$i = $i + 1;
    			
    			//On affecte un élément $item à $tableauCoffre
    			$tableauCoffre["element".$i] = $item;
    		}
    
    		//On encode en JSON
    		$response = new Response(json_encode($tableauCoffre));
    		$response->headers->set('Content-Type', 'application/json');
     
    		return $response;
        }
        
        public function nombreObjetsVueAction()
        {
        	return $this->render('AjaxAppliBundle:Principale:affichage-coffre.html.twig');
        }
    }
    affichage-coffre.html.twig

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    {% extends "::base.html.twig" %}
    
    {% block body %}
    {{ parent() }}
    
    <h2>Test de la méthode AJAX</h2>
     
    Le coffre contient <div id="nbobjets"></div> objets actuellement.
    {% endblock %}
     
    {% block javascripts %}
    
    {{ parent() }}
    
    <script type="text/javascript">
    $(document).ready(function()
    { 
    	var nombre_objet = 0;
    	
    	function valueOnline()
    	{
    		$.ajax(
    		{
    			type: 'GET',
    			data: nombre_objet,
    			url: "{{ url('ajax_appli_coffre_requete') }}",
    			success: function (data)
    			{
    				tableau_coffre = jQuery.parseJSON(data);
    
    				$("#nbobjets").html(tableau_coffre.element1.identifiant);
    			}
    		});
    	}
    
    	//Fonctionne
    	setInterval(function() { valueOnline(); }, 1000);	
    });
    </script>
    {% endblock %}
    Merci d'avance

  4. #4
    Membre confirmé
    Profil pro
    Inscrit en
    Octobre 2006
    Messages
    162
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Octobre 2006
    Messages : 162
    Par défaut
    Re,

    Finalement, c'est bon j'ai trouvé.

    En JavaScript, on n'a pas de besoin de jQuery.parseJSON, c'est fait automatiquement. De même, j'avais pas bien appelé l'élément.

    affichage-coffre.html.twig

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    {% extends "::base.html.twig" %}
    
    {% block body %}
    {{ parent() }}
    
    <h2>Test de la méthode AJAX</h2>
     
    Le coffre contient <div id="nbobjets"></div> objets actuellement.
    {% endblock %}
     
    {% block javascripts %}
    
    {{ parent() }}
    
    <script type="text/javascript">
    $(document).ready(function()
    { 
    	var nombre_objet = 0;
    	
    	function valueOnline()
    	{
    		$.ajax(
    		{
    			type: 'GET',
    			data: nombre_objet,
    			url: "{{ url('ajax_appli_coffre_requete') }}",
    			success: function (data)
    			{
    				id_element = data['element1'].identifiant;
    				
    				$("#nbobjets").html(id_element);
    			}
    		});
    	}
    
    	//Fonctionne
    	setInterval(function() { valueOnline(); }, 1000);	
    });
    </script>
    {% endblock %}

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Parser un tableau dans un fichier JSON
    Par L'aigle de Carthage dans le forum jQuery
    Réponses: 8
    Dernier message: 25/03/2014, 16h59
  2. [RegEx] Parser un tableau HTML
    Par Space Cowboy dans le forum Langage
    Réponses: 6
    Dernier message: 16/11/2010, 19h03
  3. [AJAX] Ajouter données dans un tableau json
    Par algsoft dans le forum AJAX
    Réponses: 2
    Dernier message: 26/03/2010, 00h36
  4. [Prototype] Transmission de tableau - JSON
    Par mach2Toulon dans le forum Bibliothèques & Frameworks
    Réponses: 2
    Dernier message: 02/02/2010, 14h15
  5. Réponses: 5
    Dernier message: 14/09/2008, 23h14

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo