I want to get all the images from a folder on the server, i do this with a ajax call
files = glob('assets/img/daily/*'); // get all file names
$imageArr;
foreach ($files as $file) {
$imageArr[] = $file;
}
//$imageJSON = ['img01' => $imgArr[0], 'img02' => $imgArr[1], 'img02' => $imgArr[2]];
//$jsonObj = json_encode($imageArr);
$jsonObj = json_encode($imageArr);
echo $jsonObj;
I can echo the json encode which looks like this
["assets\/img\/daily\/163.jpg","assets\/img\/daily\/168.jpg","assets\/img\/daily\/197.jpg","assets\/img\/daily\/223.jpg","assets\/img\/daily\/232.jpg","assets\/img\/daily\/260.jpg","assets\/img\/daily\/297.jpg","assets\/img\/daily\/30.jpg","assets\/img\/daily\/310.jpg","assets\/img\/daily\/333.jpg","assets\/img\/daily\/339.jpg","assets\/img\/daily\/411.jpg","assets\/img\/daily\/421.jpeg","assets\/img\/daily\/427.jpg","assets\/img\/daily\/46.jpg","assets\/img\/daily\/52.jpg","assets\/img\/daily\/86.jpg","assets\/img\/daily\/background.jpg","assets\/img\/daily\/booby.png","assets\/img\/daily\/booty.png"]
UPDATE
Here are my Javascript/AJAX/HTML
<p id="raw"></p>
<br><br>
<p id="json"></p>
<script>
var raw, json;
raw = document.getElementById("raw");
json = document.getElementById("json");
var http = new XMLHttpRequest();
var url = "ajax.php";
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function () {
if (http.readyState === 4 && http.status === 200) {
// alert(this.responseText);
var jsonObj = JSON.parse(this.responseText);
raw.textContent = this.responseText;
json.textContent = jsonObj;
}
};
http.send();
</script>
How do i access the data? i cant do jsonObj.name
since none of the outputs is named? the var jsonObj = JSON.parse(this.responseText)
i recieve looks like this
assets/img/daily/30.jpg,assets/img/daily/46.jpg,assets/img/daily/background.jpg,assets/img/daily/booby.png,assets/img/daily/booty.png,assets/img/daily/chrome.png,assets/img/daily/default.png,assets/img/daily/defaults.png
But my problem is if i try to get data from this JSON obj like echo $jsonObj[0] i will recieve this as output "["
JSON is a string. It is designed to be transmitted over HTTP, stored in files, etc. It isn't designed to be processed without being parsed first. You need to convert it to an array to be able to usefully use it.
… except you don't because the data is already available an array; you used it as input to json_encode
.
Just use the $imageArr
variable instead of $jsonObj
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.