运行 PHP,等待;运行 JavaScript,等待;然后提交表格


Run PHP, wait; run JavaScript, wait; then submit form?

我需要做什么:

我有一个包含文件输入和隐藏文本输入的上传表单。用户上传图像,图像被处理,然后发送到远程服务器进行处理,这需要几秒钟,然后远程服务器将最终的图像发送回主服务器,在那里它们保存在一个新文件夹中。JavaScript 需要访问这些新图像才能对新保存的图像进行进一步的数据处理(这也需要一秒钟(。只有在 JavaScript 完成它的事情并更新表单的输入变量之后,才能提交表单。

现在我已经让所有单独的部分工作,但一键执行所有内容已被证明是一个挑战。

我上传图片的代码:

.PHP:

 if(isset($_POST['submit'])){
 //do image manipulation and save new files using PHP
 }

.JS:

 function furtherProcessing() {
 //do further processing on newly saved images in newly created directory,
 //update hidden input variables for the form
 }

再次使用PHP:

 if(isset($_POST['input_variables'])){
 //send these variables to SQL database
 }

我知道尝试使用 JavaScript 来获取新保存的图像不是一个理想的方法,但我使用的框架仅在 JavaScript 中可用。这甚至可以一键完成吗?

你可以这样做:

在 HTML 中,将

data-processed="false"添加到表单中,如下所示:

<form action="upload.php" method="post" name="q_data" data-processed="false" enctype="multipart/form-data">

在你的jQuery中,调用这个来通过ajax提交图像:

$("form[name='q_data']").submit(function(e) {
  var $this = $(this);
  var processed = $this.data('processed')
  if (processed == false) {
    e.preventDefault();
    var formData = new FormData($(this)[0]);
    $.ajax({
      url: "upload.php", 
      type: "POST",
      data: formData ,
      async: false,
      success: function(msg) {
        //alert(msg);
        if (msg !== 'success') {
          $this.data('processed', true)
          furtherProcessing();
        }
      },
      cache: false,
      contentType: false,
      processData: false
    });
  }
});
function furtherProcessing() {
  //do further processing on newly saved images in newly created directory,
  //update hidden input variables for the form
  $("form[name='q_data']").submit();
}

some-page.php这样做:

if(isset($_POST['some-image-input-name'])){
 //do image manipulation and save new files using PHP
 return 'success'
}

但是,如果是我,我会让第一个 ajax 调用(保存图像(简单地返回保存图像的 url,然后不需要第二个 ajax 调用来检索它们,我认为这就是你现在正在做的事情