如果使用 php 变量成功上传 DropzoneJS 图像,则重定向到另一个页面

Redirect to another page if DropzoneJS image upload is success with php variable

我在表单中使用 dropzoneJS。表单还记录用户输入。下面的代码简单地显示了我在做什么。一切正常,但 php 变量未获取其值。有点像这样

if (!empty($_FILES)) {
 $imgID = submitData()//This functions upload image and write image url in database and then return ID of the affected row
}

单击表单中的提交按钮时,发生了重定向,但 $imgID 未获取其值

这是Javascript

Dropzone.options.myAwesomeDropzone = {
 autoProcessQueue: false,
 etc.. etc ..
init: function() {
 var myDropzone = this;
 $("#submit-all").click(function (e) {
   e.preventDefault();
   e.stopPropagation();
   if (myDropzone.files.length) {
    myDropzone.processQueue(); // upload files and submit the form
    } else {
    $('#my-awesome-dropzone').submit(); // submit the form
    }
  });
// Refresh page when all images are uploaded
myDropzone.on("complete", function (file) {
     if (myDropzone.getUploadingFiles().length === 0 && myDropzone.getQueuedFiles().length === 0) {
          var idvar = '<?php $imgID; ?>';
    window.location.replace("/preview.php?id="+ idvar);
    }
  });
 }
}

建议我哪里做错了。有没有替代品。

您可以将 id 作为响应发送回浏览器,并在像这样的成功事件中将其与 dropzone 一起使用。

php:(如果这个文件用于处理其他请求,可能的结构可以是这样的)

if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest' && !empty($_FILES)) 
{
    $imgID = submitData();
    echo $imgID;
}
else
{
    // The rest of your php file shoul go in here.
}

js:

Dropzone.options.myAwesomeDropzone = {

    // .........

    init: function() {
        // ........

        // On success refresh
        this.on("success", function (file) {
            var idvar = $.trim(file.xhr.response);
            window.location.replace("/preview.php?id=" + idvar);
        }
    }
}