我想从服务器上的文件夹中获取所有图像,我使用ajax调用
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;
我可以回显看起来像这样的json编码
["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"]
更新
这是我的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>
我如何访问数据?我不能jsonObj.name
,因为没有一个输出被命名?我收到的var jsonObj = JSON.parse(this.responseText)
看起来像这样
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
答案 0 :(得分:4)
但我的问题是,如果我尝试从这个JSON obj获取数据,如echo $ jsonObj [0]我将收到这个作为输出&#34; [&#34;
JSON是一个字符串。它被设计为通过HTTP传输,存储在文件等中。它不被设计为在不首先被解析的情况下被处理。您需要将其转换为数组才能有效地使用它。
...除非您没有,因为数据已经可用数组;你用它作为json_encode
的输入。
只需使用$imageArr
变量而不是$jsonObj