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

JavaScript Discussion :

Lire un json grâce à javascript


Sujet :

JavaScript

  1. #1
    Nouveau membre du Club
    Profil pro
    Inscrit en
    Février 2006
    Messages
    165
    Détails du profil
    Informations personnelles :
    Localisation : Belgique

    Informations forums :
    Inscription : Février 2006
    Messages : 165
    Points : 39
    Points
    39
    Par défaut Lire un json grâce à javascript
    Bonjour,


    A partir d'ajax, j'ai réalisé un json.
    Et je souhaiterai ensuite le lire (et le mettre en forme) par javasccript.

    Je n'y arrive.
    Je tourne en rond comme un fou.

    Pouvez-vous m'aider ?
    J'aurais aimé avoir votre aide, svp !

    Code js : 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
     
    	function plusMetal(indmetal) {
    		resetrecherche();
    		metals="";
    		if (swMetal[indmetal]==0) {
    			swMetal[indmetal]=1;
    		} else {
    			swMetal[indmetal]=0;
    		}
    		for (var ind=0; ind<swMetal.length; ind++) {
    			if (swMetal[ind] == 1) {
    				metals += ind + " ";
    			}
    		}
    		if (metals != "") {
    			metals = metals.substr(0,(metals.length-1));
    		}
    		newrecherche();
    		remplirrecherche();
    	}
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
     
    	function newrecherche() {
    		url();
    		var requete = creerRequete();
    		var pgm = "php/chargementbagues.php";
    		requete.open("POST", pgm, true);
    		requete.onreadystatechange = remplirrecherche;
    		requete.send(null);
    		document.getElementById("bloc2101").innerHTML="Chargement terminé !";
    	}
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
     
    	function remplirrecherche() {
    		if (req.readyState == 4) {
    			var doc = eval('(' + requete.responseText + ')');
    			var oTable = document.getElementById('bloc31');
    			oTable.value = doc.aaData[];
    			alert("vvv");
    		}
    	}
    Je joins aussi "chargementbagues.php"
    Code php : 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
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
     
     <?php
    	session_start();
     
    	/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
    	 * Easy set variables
    	 */
     
    	/* Array of database columns which should be read and sent back to DataTables. Use a space where
    	 * you want to insert a non-database field (for example a counter or static image)
    	 */
    	$aColumns = array();
    	$aColumns [] = 'ref_sertissure';			/* 00	*/
    	$aColumns [] = 'nofinition';				/* 01	*/
    	$aColumns [] = 'modele';					/* 02	*/
    	$aColumns [] = 'carat';						/* 03	*/
    	$aColumns [] = 'type_solitaire';			/* 04	*/
    	$aColumns [] = 'PV_HT';						/* 05	*/
    	$aColumns [] = 'statut'; 					/* 06	*/
    	$aColumns [] = 'vue_01';					/* 07	*/
    	$aColumns [] = 'max_carat_rond';			/* 08	*/
    	$aColumns [] = 'max_carat_marquise';		/* 09	*/
    	$aColumns [] = 'max_carat_emeraude';		/* 10	*/
    	$aColumns [] = 'max_carat_radiant';			/* 11	*/
    	$aColumns [] = 'max_carat_ovale';			/* 12	*/
    	$aColumns [] = 'max_carat_poire';			/* 13	*/
    	$aColumns [] = 'max_carat_coeur';			/* 14	*/
    	$aColumns [] = 'max_carat_aascher';			/* 15	*/
    	$aColumns [] = 'max_carat_cs';				/* 16	*/
    	$aColumns [] = 'max_carat_autre';			/* 17	*/				
     
    	/* Indexed column (used for fast and accurate table cardinality) */
    	$sIndexColumn = "ref_sertissure";
     
    	/* DB table to use */
    	$sTable = "sertissure_data";
     
    	/* Database connection information */
    	$gaSql['user']       = "***";
    	$gaSql['password']   = "***";
    	$gaSql['db']         = "***";
    	$gaSql['server']     = "***";
     
     
    	/* 
    	 * MySQL connection
    	 */
    	$gaSql['link'] =  mysql_pconnect( $gaSql['server'], $gaSql['user'], $gaSql['password']  ) or
    		die( 'Could not open connection to server' );
     
    	mysql_select_db( $gaSql['db'], $gaSql['link'] ) or 
    		die( 'Could not select database '. $gaSql['db'] );
     
    	mysql_set_charset( 'utf8' ); 	
     
     
    	/* 
    	 * Paging
    	 */
    	$sLimit = "";
    	if ( isset( $_GET['iDisplayStart'] ) && $_GET['iDisplayLength'] != '-1' )
    	{
    		$sLimit = "LIMIT ".intval( $_GET['iDisplayStart'] ).", ".
    			intval( $_GET['iDisplayLength'] );
    	}
     
     
    	/*
    	 * Ordering
    	 */
    	$sOrder = "";
    	if ( isset( $_GET['iSortCol_0'] ) )
    	{
    		$sOrder = "ORDER BY  ";
    		for ( $i=0 ; $i<intval( $_GET['iSortingCols'] ) ; $i++ )
    		{
    			if ( $_GET[ 'bSortable_'.intval($_GET['iSortCol_'.$i]) ] == "true" )
    			{
    				$sOrder .= "`".$aColumns[ intval( $_GET['iSortCol_'.$i] ) ]."` ".
    					($_GET['sSortDir_'.$i]==='asc' ? 'asc' : 'desc') .", ";
    			}
    		}
     
    		$sOrder = substr_replace( $sOrder, "", -2 );
    		if ( $sOrder == "ORDER BY" )
    		{
    			$sOrder = "";
    		}
    	}
     
     
    	/* 
    	 * Filtering
    	 * NOTE this does not match the built-in DataTables filtering which does it
    	 * word by word on any field. It's possible to do here, but concerned about efficiency
    	 * on very large tables, and MySQL's regex functionality is very limited
    	 */
    	$sWhere = "";
    	if ( $_GET['sSearch'] != "" )
    	{
    		$sWhere = "(";
    		$aWords = preg_split('/\s+/', $_GET['sSearch']);
    		for ( $j=0 ; $j<count($aWords) ; $j++ )
    		{
    			if ( $aWords[$j] != "" )
    			{
    				$sWhere .= "(";
    				for ( $i=0 ; $i<count($aColumns) ; $i++ )
    				{
    					$sWhere .= "`".$aColumns[$i]."` LIKE '%".mysql_real_escape_string( $aWords[$j] )."%' OR ";
    				}
    				$sWhere = substr_replace( $sWhere, "", -3 );
    				$sWhere .= ") AND ";
    			}
    		}
     
    		$sWhere = substr_replace( $sWhere, "", -5 );
    		$sWhere .= ")";
    	}
     
    	/* Individual column filtering */
    	$sColumnWhere = "";
    	for ( $i=0 ; $i<count($aColumns) ; $i++ )
    	{	
    		if ( $_GET['sSearch_'.$i] != "" )
    		{
    			$aWords = preg_split('/\s+/', $_GET['sSearch_'.$i]);
    			$sColumnWhere .= "(";
    			for ( $j=0 ; $j<count($aWords) ; $j++ )
    			{
    				if ( $aWords[$j] != "" )
    				{
    					$sColumnWhere .= "`".$aColumns[$i]."` = '".mysql_real_escape_string( $libelle[ $i ][ $aWords[$j] ] )."' OR ";
    				}
    			}
    			$sColumnWhere = substr_replace( $sColumnWhere, "", -3 );
    			$sColumnWhere .= ") AND ";
    		}
    		if ( $_GET['sStart_'.$i] != "" AND $_GET['sEnd_'.$i] != "" )
    		{
    			$sColumnWhere .= "(";
    			$sColumnWhere .= "`".$aColumns[$i]."` >= '".mysql_real_escape_string( $_GET['sStart_'.$i] )."' AND `".$aColumns[$i]."` <= '".mysql_real_escape_string( $_GET['sEnd_'.$i] )."' ";
    			$sColumnWhere .= ") AND ";
    		}
    	}
     
    	if ( $sColumnWhere != "" ) {
    		$sColumnWhere = substr_replace( $sColumnWhere, "", -5 );
    		if ( $sWhere == "" ) {
    			$sWhere = $sColumnWhere;
    		} else {
    			$sWhere .= " AND ".$sColumnWhere;
    		}
    	}
     
    	if ( $sWhere != "" )
    	{
    		$sWhere = "WHERE ".$sWhere;
    	}
     
     
    	/*
    	 * SQL queries
    	 * Get data to display
    	 */
    	$sQuery = "
    	 SELECT SQL_CALC_FOUND_ROWS `".str_replace(" , ", " ", implode("`, `", $aColumns))."` 
    		FROM   $sTable
    		$sWhere
    		$sOrder
    		$sLimit
    		";
    	$rResult = mysql_query( $sQuery, $gaSql['link'] ) or die(mysql_error());
     
    	/* Data set length after filtering */
    	$sQuery = "
    		SELECT FOUND_ROWS()
    	";
    	$rResultFilterTotal = mysql_query( $sQuery, $gaSql['link'] ) or die(mysql_error());
    	$aResultFilterTotal = mysql_fetch_array($rResultFilterTotal);
    	$iFilteredTotal = $aResultFilterTotal[0];
     
    	/* Total data set length */
    	$sQuery = "
    		SELECT COUNT(`".$sIndexColumn."`)
    		FROM   $sTable
    	";
    	$rResultTotal = mysql_query( $sQuery, $gaSql['link'] ) or die(mysql_error());
    	$aResultTotal = mysql_fetch_array($rResultTotal);
    	$iTotal = $aResultTotal[0];
     
     
    	/*
    	 * Output
    	 */
    	$output = array(
    		"sEcho" => intval($_GET['sEcho']),
    		"iTotalRecords" => $iTotal,
    		"iTotalDisplayRecords" => $iFilteredTotal,
    		"aaData" => array()
    	);
     
    	while ( $aRow = mysql_fetch_array( $rResult ) )
    	{
    				$row = array();
    				$row[] = trim($aRow[ 'ref_sertissure' ]);
    				$row[] = trim($aRow[ 'nofinition' ]);
    				$row[] = trim($aRow[ 'modele' ]);
    				$inter = trim($aRow[ 'carat' ]);
    				$row[] = number_format($inter, 2, ',', ' ');
    				$row[] = trim($aRow[ 'type_solitaire' ]);
    				$inter = trim($aRow[ 'PV_HT' ]);
    				$row[] = number_format($inter, 0, ',', ' ');
    				$row[] = trim($aRow[ 'statut' ]);
    				$row[] = trim($aRow[ 'vue_01' ]);
    				$inter = trim($aRow[ 'max_carat_rond' ]);
    				$row[] = number_format($inter, 2, ',', ' ');
    				$inter = trim($aRow[ 'max_carat_marquise' ]);
    				$row[] = number_format($inter, 2, ',', ' ');
    				$inter = trim($aRow[ 'max_carat_emeraude' ]);
    				$row[] = number_format($inter, 2, ',', ' ');
    				$inter = trim($aRow[ 'max_carat_radiant' ]);
    				$row[] = number_format($inter, 2, ',', ' ');
    				$inter = trim($aRow[ 'max_carat_ovale' ]);
    				$row[] = number_format($inter, 2, ',', ' ');
    				$inter = trim($aRow[ 'max_carat_poire' ]);
    				$row[] = number_format($inter, 2, ',', ' ');
    				$inter = trim($aRow[ 'max_carat_coeur' ]);
    				$row[] = number_format($inter, 2, ',', ' ');
    				$inter = trim($aRow[ 'max_carat_aascher' ]);
    				$row[] = number_format($inter, 2, ',', ' ');
    				$inter = trim($aRow[ 'max_carat_cs' ]);
    				$row[] = number_format($inter, 2, ',', ' ');
    				$inter = trim($aRow[ 'max_carat_autre' ]);
    				$row[] = number_format($inter, 2, ',', ' ');
    				$row[] = "<a href='javascript:envoiDetails(".trim($aRow[ 'ref_sertissure' ]).");'><span class='voir'>Détails</span></a>";
    				$output['aaData'][] = $row;
    	}
     
    	echo json_encode( $output );
    ?>

  2. #2
    Rédacteur/Modérateur

    Avatar de SpaceFrog
    Homme Profil pro
    Développeur Web Php Mysql Html Javascript CSS Apache - Intégrateur - Bidouilleur SharePoint
    Inscrit en
    Mars 2002
    Messages
    39 640
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 74
    Localisation : Royaume-Uni

    Informations professionnelles :
    Activité : Développeur Web Php Mysql Html Javascript CSS Apache - Intégrateur - Bidouilleur SharePoint
    Secteur : Industrie

    Informations forums :
    Inscription : Mars 2002
    Messages : 39 640
    Points : 66 669
    Points
    66 669
    Billets dans le blog
    1
    Par défaut
    => JQuery ...

  3. #3
    Nouveau membre du Club
    Profil pro
    Inscrit en
    Février 2006
    Messages
    165
    Détails du profil
    Informations personnelles :
    Localisation : Belgique

    Informations forums :
    Inscription : Février 2006
    Messages : 165
    Points : 39
    Points
    39
    Par défaut
    Peux-tu m'aider un peu plus ? stp ?
    Comment mettre en place ce "getJSon" ?

  4. #4
    Rédacteur/Modérateur

    Avatar de SpaceFrog
    Homme Profil pro
    Développeur Web Php Mysql Html Javascript CSS Apache - Intégrateur - Bidouilleur SharePoint
    Inscrit en
    Mars 2002
    Messages
    39 640
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 74
    Localisation : Royaume-Uni

    Informations professionnelles :
    Activité : Développeur Web Php Mysql Html Javascript CSS Apache - Intégrateur - Bidouilleur SharePoint
    Secteur : Industrie

    Informations forums :
    Inscription : Mars 2002
    Messages : 39 640
    Points : 66 669
    Points
    66 669
    Billets dans le blog
    1
    Par défaut
    as tu lu les tuto sur le forum jquery sur la mise en place de jquery ...
    getJSON est une methode native de JQuery

  5. #5
    Nouveau membre du Club
    Profil pro
    Inscrit en
    Février 2006
    Messages
    165
    Détails du profil
    Informations personnelles :
    Localisation : Belgique

    Informations forums :
    Inscription : Février 2006
    Messages : 165
    Points : 39
    Points
    39
    Par défaut
    En fait, plus exactement, mon problème
    consiste dans la lecture des lignes de aaData.
    Peux-tu m'y aider ?
    Soit en javascript ? Soit en jquery, si c'est plus simple ?
    Merci d'avance.

    Voilà pourquoi je te demande un peu de code pour me "dépatouiller" !
    A l'aide, stp.

  6. #6
    Rédacteur/Modérateur

    Avatar de SpaceFrog
    Homme Profil pro
    Développeur Web Php Mysql Html Javascript CSS Apache - Intégrateur - Bidouilleur SharePoint
    Inscrit en
    Mars 2002
    Messages
    39 640
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 74
    Localisation : Royaume-Uni

    Informations professionnelles :
    Activité : Développeur Web Php Mysql Html Javascript CSS Apache - Intégrateur - Bidouilleur SharePoint
    Secteur : Industrie

    Informations forums :
    Inscription : Mars 2002
    Messages : 39 640
    Points : 66 669
    Points
    66 669
    Billets dans le blog
    1
    Par défaut
    en jquery c'est super simple

    une simple requete getJONS ver suin fichier php qui retourne un json_encode et tu recupères directement un json exploitable sur lequel tu pourras boucler avec un for

  7. #7
    Nouveau membre du Club
    Profil pro
    Inscrit en
    Février 2006
    Messages
    165
    Détails du profil
    Informations personnelles :
    Localisation : Belgique

    Informations forums :
    Inscription : Février 2006
    Messages : 165
    Points : 39
    Points
    39
    Par défaut
    Exceptionnellement,
    ne peux-tu pas me "dépatouiller" cela ?
    stp !
    stp !

  8. #8
    Modérateur

    Avatar de NoSmoking
    Homme Profil pro
    Inscrit en
    Janvier 2011
    Messages
    17 060
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Isère (Rhône Alpes)

    Informations forums :
    Inscription : Janvier 2011
    Messages : 17 060
    Points : 44 585
    Points
    44 585
    Par défaut
    Bonjour,
    attendu que tu utilises jQuery autant utiliser getJson, leur documentation étant bien faite les exemples renseignés devraient te satisfaire.

    jQuery.getJSON()

    Sinon lorsque tu as
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    var objet = eval('(' + requete.responseText + ')');
    tu peux parcourir ton objet grâce à une boucle for...in du type
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    var result = '';
    for( var i in objet){
      result += i +'=' +objet[i] +'\r';
    }
    alert( result);// pour voir

  9. #9
    Rédacteur/Modérateur

    Avatar de SylvainPV
    Profil pro
    Inscrit en
    Novembre 2012
    Messages
    3 375
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Novembre 2012
    Messages : 3 375
    Points : 9 944
    Points
    9 944
    Par défaut
    Il ne faut pas utiliser eval mais JSON.parse. Ce que fait automatiquement en arrière-plan la méthode $.getJSON.

  10. #10
    Nouveau membre du Club
    Profil pro
    Inscrit en
    Février 2006
    Messages
    165
    Détails du profil
    Informations personnelles :
    Localisation : Belgique

    Informations forums :
    Inscription : Février 2006
    Messages : 165
    Points : 39
    Points
    39
    Par défaut
    Peux-tu m'aider aussi avec la dernière solution ?
    Ceci n'est pas encore très clair pour moi !
    A l'aide svp.

    De plus, j'ai oublié de préciser que je souhaiterai appliquer la notion de tri,
    pour toutes les variables de mon JSON... Raison pour laquelle, je me suis très fortement inspiré d'un script à la sauce "dataTables" (server-processing)

  11. #11
    Rédacteur/Modérateur

    Avatar de SylvainPV
    Profil pro
    Inscrit en
    Novembre 2012
    Messages
    3 375
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Novembre 2012
    Messages : 3 375
    Points : 9 944
    Points
    9 944
    Par défaut
    Commence par ceci pour t'assurer que ton JSON est valide. Aussi, il faut que tu apprennes à te servir des outils de développement Javascript de ton navigateur comme la console, les breakpoints etc...

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
     
    if (req.readyState == 4) {
       try {
    	var json = JSON.parse(req.responseText);
            console.log("JSON valide");
            console.dir(json); //voir le résultat en console
       } catch(err){
           console.log("JSON invalide");
           console.error(err);
       }
    }

Discussions similaires

  1. Lire fichier JSON dans JavaScript
    Par alaninho dans le forum Général JavaScript
    Réponses: 6
    Dernier message: 15/03/2013, 07h06
  2. Lire json en JavaScript
    Par drummmer dans le forum Général JavaScript
    Réponses: 3
    Dernier message: 23/01/2013, 14h29
  3. [Prototype] Lire du JSON en javascript
    Par sliderman dans le forum Bibliothèques & Frameworks
    Réponses: 9
    Dernier message: 18/02/2008, 10h44
  4. [AJAX] Récupération d'un fichier JSON avec javaScript
    Par guerin dans le forum Général JavaScript
    Réponses: 1
    Dernier message: 26/11/2006, 19h05
  5. Lire un xml avec javascript et generer code html ?
    Par zevince dans le forum Général JavaScript
    Réponses: 8
    Dernier message: 04/04/2006, 11h45

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