1

I am trying to append a the variable imagename but instead of displaying a file name, it is appending numbers '0' then break then '1'. I want to know why is it appending these numbers and not the file names? The imagename variable loops through the imageNameArray variable which contains a $_SESSION variable which retrieves the name of the files which have been uploaded and that $_SESSION variable is retrieved from the php script where the files are uploaded.

Below is the javascript code where the appending occurs:

  function stopImageUpload(success){

var imageNameArray = <?php echo json_encode(isset($_SESSION ['fileImage']) ? $_SESSION ['fileImage'] : null); ?>;
 var result = '';



if (success == 1){
result = '<span class="msg">The file was uploaded successfully!</span><br/><br/>';
for (imagename in imageNameArray)
            {
$('.listImage').append(imageNameArray[imagename]+ '<br/>');

             }

              }
 else {
 result = '<span class="emsg">There was an error during file upload!</span><br/><br/>';
              }

 return true;   
 }

Below is the php script where it uploads a file and where the $_SESSION variable retrieve its file name:

 <?php

    session_start();

    $result = 0;
    $errors = array ();
    $dirImage = "ImageFiles/";


if (isset ( $_FILES ['fileImage'] ) && $_FILES ["fileImage"] ["error"] == UPLOAD_ERR_OK) {

$fileName = $_FILES ['fileImage'] ['name'];

$fileExt = pathinfo ( $fileName, PATHINFO_EXTENSION );
$fileExt = strtolower ( $fileExt );


$fileDst = $dirImage . DIRECTORY_SEPARATOR . $fileName;

        if (count ( $errors ) == 0) {
            if (move_uploaded_file ( $fileTemp, $fileDst )) {
                $result = 1;


            }
        }

    }

$_SESSION ['fileImage'][] = $_FILES ['fileImage']['name'];

    ?>

<script language="javascript" type="text/javascript">window.top.stopImageUpload(<?php echo $result;?>);</script>
4

2 回答 2

2

因为您在for in数组上使用循环,所以imageName将等于数组的索引,而不是它的值。很像for (i in window),我将在其中列出窗口对象的所有方法和属性。

由于这是一个数组,我强烈建议您使用一种for(i=0;i<arr.length;i++)循环,因为它更安全……在这两种情况下,您都需要替换

$('.listImage').append(imagename + '<br/>');

$('.listImage').append(imageNameArray[imagename]+ '<br/>');

编辑

for循环可能对您不起作用,因为我遗漏了一点,因为我认为它很明显。不幸的是,显而易见的事情很容易被忽视......正如格雷格向我指出的那样(谢谢 m8):

$('.listImage').append(imageNameArray[i]+ '<br/>');

如果您使用 for(i...) 样式循环。为了清楚起见,我将添加完整的循环:

for(var i=0;i<imageNameArray.length;i++)
{
    $('.listImage').append(imageNameArray[i]+ '<br/>');
}

为了帮助您进一步找出仅显示一个 img 名称可能导致问题的原因,请在循环开始之前添加此问题:console.log(imageArrayName);并查看您的控制台。数组是否包含超过 1 个元素?它说什么?当您使用它时,也请尝试添加此行:console.log((imageArray instanceof Array ? 'for' : 'for-in'));. 在您发布的 JavaScript 函数中的任何位置添加此行,但在循环之外,以避免使您的控制台过于混乱......

让我知道你发现了什么

于 2012-04-26T18:43:00.557 回答
0

因为for (var in array)迭代数组的索引。你应该做

$('.listImage').append(imageNameArray[imagename] + '<br/>');
于 2012-04-26T18:41:14.990 回答