我有一個ajax應用程序。它基本上傳圖像到一個文件夾,然後PHP抓住它們並將它們放入一個數組中。從那裏它是json_encodeded並通過回聲發回。 alert(responseText)
給了我json版本。當我設置一個變量爲json.parse()
,console.log()
它作爲一個數組出現得很好。該陣列基本上是這樣的:PHP數組到JSON對象 - 如何操作?
1 IMAGE1.jpg
2 IMAGE2.jpg
3 IMAGE3.jpg
4 IMAGE4.jpg
5 IMAGE5.jpg
等
我的理解現在是一個JavaScript/JSON對象。不幸的是,我找不到任何有關操作此對象的信息來獲取所有圖像名稱和最後一個真正成功或失敗上傳的數組類型。任何人都可以向我指出一些文檔或一種方法來操縱這個並將信息外推到一個數組中。最後,我試圖動態顯示這些圖像,但我假設通過上傳他們並不都具有相同的名稱。
所以我希望抓住所有的.jpg/.png。/ gif等,並抓住這些文件名,然後使用innerHTML
創建一串<img>
使用循環正確的文件名標記。同樣,處理數組中的最後一塊,只是文本說明上傳是否完全成功。
我不應該使用JSON嗎?我的代碼如下。
PHP
$dirhandler = opendir(UPLOAD_DIR);
//create handler to directory
//read all the files from directory
$nofiles=0;
while ($file = readdir($dirhandler)) {
//if $file isn't this directory or its parent
//echo "FILE SYSTEM: " . $file . "<br/>";
//add to the $files array
if ($file != '.' && $file != '..') {
$nofiles++;
$files[$nofiles]=$file;
} //end of if loop
} //end of while loop
//json_encode($files);
if (!$success) {
$nofiles++;
$files[$nofiles] = "Unable to upload file";
exit;
} else {
$nofiles++;
$files[$nofiles] = "File Upload Successfully";
}
echo json_encode($files);
JAVASCRIPT
if (xhr.readyState === 4 && xhr.status === 200) {
progressBar.value="100";
progressText = "Upload Complete!";
progressStatus.innerHTML = progressText;
var imageNames = JSON.parse(xhr.responseText);
alert(imageNames);
} else if (xhr.readyState === 0 || xhr.readyState === 1) {
progressBar.value = "25";
progressText = "Starting Upload..";
progressStatus.innerHTML = progressText;
} else if (xhr.readyState === 2) {
progressBar.value = "50";
progressText = "Almost Done...";
progressStatus.innerHTML = progressText;
} else if (xhr.readyState === 3) {
progressBar.value = "75";
progressText = "So Close!";
progressStatus.innerHTML = progressText;
} else if (xhr.status === 404 || xhr.status === 500) {
alert("Your Upload Request failed.");
}
我也想說明一下。我沒有使用jQUERY或任何其他JavaScript或PHP庫。 – kmalik
那你怎麼使用'JSON.parse'? – h2ooooooo
'JSON.parse'適用於任何現代瀏覽器。 –