2017-06-16 21 views
0

我想從服務器上的文件夾中獲得的所有圖像,我這樣做有一個Ajax調用數組的Javascript/AJAX JSON編碼 - 如何在recived時使用數據?

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"] 

UPDATE

這裏是我的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

嘗試的var_dump($ jsonObj) – Arcv

+4

'$ jsonObj'是一個字符串嗎?所以'$ jsonObj [0]'是該字符串的第一個字符,它是'「[」' – Halcyon

+0

http://benalman.com/news/2010/03/theres-no-such-thing-as-a- json/ – Quentin

回答

4

但我的問題是,如果我試圖從這個JSON OBJ樣回聲$ jsonObj數據[0]我會收到此作爲輸出「[」

JSON是一個字符串。它被設計爲通過HTTP傳輸,存儲在文件等中。它不是被設計爲不被首先分析處理。您需要將其轉換爲數組才能夠有用地使用它。

...除非你沒有,因爲數據是已經可用數組;您將它用作json_encode的輸入。

只需使用$imageArr變量而不是$jsonObj

+0

我將實際回顯json字符串的ajax調用 – Javaish

+0

@Javaish - 然後回顯字符串,而不是試圖循環它。 – Quentin

+0

我已更新問題 – Javaish