使用PHP上传Dropzone JS文件时,调用PHP中的Javascript函数

Call Javascript function in PHP during Dropzone JS file upload with PHP

本文关键字:PHP 调用 中的 函数 Javascript 文件 上传 Dropzone JS 使用      更新时间:2023-09-26

我正试图在PHP文件上传中调用一个Javascript函数。PHP方法取自这里:

Dropzone JS&PHP

<?php
$post_id = $_GET['post_id'];
$ds = DIRECTORY_SEPARATOR;
$storeFolder = '/images/$post_id';
if (!empty($_FILES)) {
$tempFile = $_FILES['file']['tmp_name'];           
$targetPath = dirname( __FILE__ ) . $ds. $storeFolder . $ds;
$targetFile =  $targetPath. $_FILES['file']['name'];
move_uploaded_file($tempFile,$targetFile);
echo "<script type='text/javascript'>showfeaturedimg('$post_id');</script>";
}
?>

文件上传工作没有问题。

我尝试了多种方法,在不同的论坛上都找到了,但都不起作用:

echo "<script language='javascript'>showfeaturedimg('$post_id');</script>";
or
echo "<script>showfeaturedimg('''$post_id''');</script>";

showfeaturedimg()函数只需进行AJAX调用,即可从数据库中检索存储的图像并将其显示在页面上,而无需重新加载页面。

此外,我们还尝试向Dropzone的queuecomplete添加一个javascript函数调用,但也不起作用:

<form action="upload-post.php?post_id=<?php echo $post_id;?>" class="dropzone" id="news-dropzone">
<div class="fallback">
<input name="file" type="file" multiple="multiple" />
</div>
</form>
<script>
Dropzone.options.dropzoneJsForm = {
init: function () {
this.on("success", function (file) {
alert("All files have uploaded ");
});
}
};
</script>

我做错了什么?

首先,您需要将带有dropzone配置的脚本放入主体中,否则dropzone将自动检测您的表单,并使用默认选项创建它。

然后,在成功事件中,您可以访问file.xhr.response中的服务器响应,或者如果您传递第二个参数,该参数将成为响应本身,在本例中,警报将显示您在php文件中打印的脚本。

<body>
......
    <script>
        Dropzone.options.newsDropzone= {
            init: function () {
                this.on("success", function (file, response) {
                    alert(response); // or alert(file.xhr.response);
                })
            }
        };
    </script>
</body>

如果你想执行响应而不是在警报中显示它,只需将它附加到html中,任何地方都可以。

或者,如果你喜欢,你可以使用jQuery插件来配置dropzone,但为了首先做到这一点,你需要将autodiscover设置为false,这里有一个例子:

<script>
    Dropzone.autoDiscover = false;
    $('#news-dropzone').dropzone({
         init: function () {
             this.on("success", function (file, response) {
                 alert(response); // or alert(file.xhr.response);
             })
         }
    });
</script>

注意:还要检查控制台,因为我认为您的初始代码应该会出现错误。