Trying to iterate through following JSON object which i have encode in PHP, by looping through a directory containing png files. I have no luck in iterating the JSON in getLayersObject. I tried the following code and it didn't work. Any suggestions?
<?php $dir = "layers"; $layers = array(); if (is_dir($dir)) { if ($dh = opendir($dir)) { while (($file = readdir($dh)) !== false) { if ($file != '.' && $file != '..') { array_push($layers, $file); } } closedir($dh); } } echo json_encode(array('phone' => $layers), JSON_FORCE_OBJECT); ?> JavaScript
var Layers = (function () { var layers = []; var mobileLayer = ''; var initialisering = function(){ var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { var myObj = JSON.parse(xmlhttp.responseText); layers.push(myObj); } }; xmlhttp.open("GET", "http://localhost/layers/get_layers.php", true); xmlhttp.send(); getLayersObject(); }; var getLayersObject = function(){ mobileLayer = document.getElementsByClassName('layer'); Object.keys(layers.phone).forEach(function(key,index) { console.log(key, layers.phone[index]); }); } return { initialisering: initialisering }; })(); window.addEventListener("load", Layers.initialisering()); JSON result
{ "phone": { "0": "11.png", "1": "12.png", "2": "14.png", "3": "15.png", "4": "4.png", "5": "7.png", "6": "9.png", "7": "front_kamera.png" } }
jsontag?