Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
202 views
in Technique[技术] by (71.8m points)

javascript - Display files in directory using PHP and jQuery

I am trying to use PHP and jQuery to display files in a directory.

I have incorporated Datatables to list all records in a database. Some of these records have files linked to them. The user would click a link which opens a modal window which should then display all the files in that record's directory.

Starting with the PHP

<?php
if(isset($_POST['editpartnercode']))
{
    $partnerCode = $_POST['editpartnercode'];

    $dir = "D:/CargoDocsPDFs/" . $partnerCode;

    $ffs = scandir($dir);

    foreach($ffs as $ff)
    {               
        if($ff != '.' && $ff != '..')
        {   
            echo $ff;
            // echo json_encode($out); // <-this didn't work either
        }
    }       
}
?>

Here is the jQuery that uses $.post to pass the editpartnercode variable:

$.post('process/displayFiles.php', {editpartnercode:editpartnercode}, function(data)
{
    console.log(data);
    var obj = JSON.parse(data);
    $('#allFiles').empty();
    var htmlToInsert = obj.map(function (item)
    {
        return '<li><b>' + item.ff + '</b></li>';
    }).join('');
    $('#allFiles').html(htmlToInsert);      
});

The HTML looks like this:

<div class="row">
    <div class="col-lg-12">
        <p>Uploaded Files</p>
        <ul id="allFiles">
        </ul>
    </div>
</div>

I can see the file names in the console, but I am also getting this error:

VM2087:1 Uncaught SyntaxError: Unexpected token T in JSON at position 0
at JSON.parse (<anonymous>)
at Object.success (genhome.js:210)
at u (jquery.js:2)
at Object.fireWith [as resolveWith] (jquery.js:2)
at k (jquery.js:2)
at XMLHttpRequest.<anonymous> (jquery.js:2)

To reiterate, all I am trying to do is list the files associated with the editpartnercode (which is the directory name).

What am I missing that will get rid of that error and print the files on the screen?

Edit

Here is how the files are being printed in the console:

TEST1234567.TIFFTEST1234567_121218_100637.TIFFThumbs.db
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When trying to return json array from pure php script you could also set the header of the response

header('Content-type: application/json');
echo json_encode($ff);

But I would also populate the array first and return whole result in the end.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...