2013-01-15 26 views
0

我有一個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."); 
     } 
+0

我也想說明一下。我沒有使用jQUERY或任何其他JavaScript或PHP庫。 – kmalik

+0

那你怎麼使用'JSON.parse'? – h2ooooooo

+2

'JSON.parse'適用於任何現代瀏覽器。 –

回答

0

imageNames是什麼,特殊的對象 - 使用它就像你使用任何普通的JavaScript對象。例如:imageNames[2]會給你第二個圖像名稱。

但是,如果您生成一個數組,json_encode()將理解爲實際的JS數組,那麼您的生活將會更容易。在你的PHP,包括每個圖像,而不是使用顯式索引的條目:

$files = array(); 
$entries = scandir(UPLOAD_DIR); 
foreach ($entries as $entry) { 
    if (is_file(UPLOAD_DIR.'/'.$entry)) { 
     $files[] = $entry; 
    } 
} 
if (!$files) { 
    // signal an error with an actual HTTP error code! 
    header('Content-Type: application/json', false, 500); 
    echo json_encode(array('error'=>'upload failed')); 
} else { 
    header('Content-Type: application/json'); 
    echo json_encode($files); 
} 

不過,我懷疑,當你處理它們,你應該收集你的文件名。使用帶有輸入元素的上傳表單,如<input type="file" name="images[]">,然後上傳至以下腳本:

function process_uploaded_files($files, $destdir, $nametmpl) { 
    $moved = array(); 
    foreach ($files['error'] as $key => $error) { 
     $newname = FALSE; 
     if ($error===UPLOAD_ERR_OK) { 
      $source = $files['tmp_name'][$key]; 
      $destname = sprintf($nametmpl, $key); 
      $dest = "{$destdir}/{$destname}"; 
      if (move_uploaded_file($source, $dest)) { 
       // success! 
       $newname = $destname; 
      } 
     } 
     $moved[$key] = $newname; 
    } 
    return $moved; 
} 

function filename_to_url($filename) { 
    // or whatever 
    return ($filename) ? '/images/'.$filename : $filename; 
}  

$uploaded_files = process_uploaded_files($_FILES['images'], UPLOAD_DIR, 'Image%03d'); 

// you should always return URLs of resources (not bare filenames) to be RESTful 
$new_urls = array_map('filename_to_url', $uploaded_files); 
header('Content-Type: application/json'); 
echo json_encode($new_urls); 
+0

我試過做imageNames.length,似乎沒有工作。雖然我確定我可能必須編寫一個函數來獲取對象的大小,因爲它不是數組。我認爲這就是阻止我的原因。感謝您的幫助。 – kmalik

+0

如果PHP數組按順序索引從0開始的數字鍵而沒有任何漏洞,那麼'json_encode'只會生成一個JS/JSON數組('[]')。否則它會產生一個對象('{}')。 –

+0

這是很好的知道下一次。謝謝。 – kmalik