上传后没有显示Ajax数据

时间:2017-09-25 11:27:15

标签: javascript php jquery ajax

目前我的整个代码工作几乎完美无缺,上传成功上传后ajax数据没有显示在我的网页上。

下面是我正在使用的代码(完全),因为我很新,并且一直在审查各种堆栈流量帖子,以指导我构建它。

很抱歉下面没有结构..我不知道如何适应堆栈溢出结构要求..

实际表格输入/提交

<form action="upload2.php" class="upload" enctype="multipart/form-data" id="upload" method="post" name="upload">
    <fieldset>
        <legend>Uplaod Files</legend> <input id="file" multiple name="file[]" required="" type="file"> <input id="submit" name="submit" type="submit" value="upload">
    </fieldset>
    <div class="bar">
        <span class="bar-fill" id="pb"><span class="bar-fill-text" id="pt"></span></span>
    </div>
    <div class="uploads" id="uploads"></div>
</form>

这是我用来上传文件的PHP代码。

<?
header('Content-Type: application/json');

$upload = [];
$allowed = ['mp3', 'm4a'];

$succeeded = [];
$failed = [];

if (!empty($_FILES['file'])) {
    foreach ($_FILES['file']['name'] as $key => $name) {
        if ($_FILES['file']['error'][$key] === 0) {
            $temp = $_FILES['file']['tmp_name'][$key];
            $file_name = $_FILES['file']['name'][$key];
            $file_size = $_FILES['file']['size'][$key];

            $ext = explode('.', $name);
            $ext = strtolower(end($ext));
            $s = substr(str_shuffle(str_repeat("0123456789abcdefghijklmnopqrstuvwxyz", 4)), 0, 4);
            $file = $s . '.' . $ext;
            $data = $file_name . PHP_EOL . $file_size;
            file_put_contents('d/' . $s . '.txt', $data);
            if (in_array($ext, $allowed) === true && move_uploaded_file($temp, "v/{$file}") === true) {
                $succeeded[] = array(
                    'name' => $name,
                    'file' => $file,
                );
            } else {
                $failed[] = array(
                    'name' => $name
                );
            }
        }
    }
    if (isset($_POST['ajax'])) {
        echo json_encode(array(
            'succeeded' => $succeeded,
            'failed' => $failed
        ));
    }
}

下面是javascript事件监听器+来自ajax的返回数据

document.getElementById('submit').addEventListener('click', function (e) {
    e.preventDefault();
    var f = document.getElementById('file'),
        pb = document.getElementById('pb'),
        pt = document.getElementById('pt');
    app.uploader({
        files: f,
        progressBar: pb,
        progressText: pt,
        processor: 'upload2.php',
        finished: function (data) {
            var uploads = document.getElementById('uploads'),
                succeeded = document.createElement('div'),
                failed = document.createElement('div'),
                anchor,
                span,
                x;
            if (data.failed.length) {
                failed.innerHTML = '<p>file didnt upload<\/p>';
            }
            uploads.innerText = '';
            for (x = 0; x < data.succeeded.length; x = x + 1) {
                anchor = document.createElement('a');
                anchor.href = 'uploads/' + data.succeeded[x].file;
                anchor.innerText = data.succeeded[x].name;
                archor.target = '_blank';
                console.log(anchor);
                succeeded.appendChild(anchor);
            }
            uploads.appendChild(succeeded);
        },
    });
});

以下是我们用于ajax的javascript(我认为问题在这里,但我一直在审核它,而且我无法找到问题。)

var app = app || {};
(function (o) {
    "use strict";
    var ajax, getFormData, setProgress;
    ajax = function (data) {
        var xmlhttp = new XMLHttpRequest(),
            uploaded;
        xmlhttp.addEventListener('readystatechange', function () {
            if (this.readystate === 4) {
                if (this.status === 200) {
                    uploaded = JSON.parse(this.response);
                    if (typeof o.options.finished === 'function') {
                        o.options.finished(uploaded);
                    }
                } else {
                    if (typeof o.options.error === 'function') {
                        o.options.error();
                    }
                }
            }
        });
        xmlhttp.upload.addEventListener('progress', function (event) {
            var percent;
            if (event.lengthComputable === true) {
                percent = Math.round((event.loaded / event.total) * 100);
                setProgress(percent);
            }
        });
        xmlhttp.open('post', o.options.processor);
        xmlhttp.send(data);
    };
    getFormData = function (source) {
        var data = new FormData(),
            i;
        for (i = 0; i < source.length; i = i + 1) {
            data.append('file[]', source[i]);
        }
        data.append('ajax', true);
        return data;
    };
    setProgress = function (value) {
        if (o.options.progressBar !== undefined) {
            o.options.progressBar.style.width = value ? value + '%' : 0;
        }
        if (o.options.progressText !== undefined) {
            o.options.progressText.innerText = value ? value + '%' : '';
        }
    };
    o.uploader = function (options) {
        o.options = options;
        if (o.options.files !== undefined) {
            ajax({});
            ajax(getFormData(o.options.files.files));
        }
    }
}(app));

我的文件正在上传,进度条正常工作,并且在重定向到e.preventDefault();时无法返回upload2.php我能够看到json的内容我真的不喜欢#39;不知道我的问题可能是什么..

1 个答案:

答案 0 :(得分:0)

首先,您在中输入错误

archor.target = '_blank';

可能会抛出错误并停止其他代码执行

您还可以通过浏览器中的元素检查器检查您的上传 div是否可见。

如果console.log没有显示任何内容 - 你的意思是它甚至没有调用它或它显示 undefined ?如果它根本没有显示,那么查看使用 data.succeeded.length param作为限制的for - 也许它等于0,因此从不调用console.log