将PHP变量传递给JS变量

时间:2020-02-27 11:36:45

标签: javascript php html variables

我知道这个问题已经问了很多遍了,但是我尝试过的所有方法都无效。

HERE HERE HERE HERE 我读过许多其他文章和文章,没有任何效果。

所以,我想做的就是将变量传递给JS文件或HTML文件。

此变量是“ fileNewName”,基本上,当上载图像时,其名称将被替换为单数,以便如果两个图像具有相同的名称,则其中一个不会被覆盖。

然后,我需要将此“ fileNewName”返回给HTML,以便与img对象一起显示它。我想避免将index.HTML文件更改为index.PHP,但据我所知,我将不得不在某些时候这样做,并且可能使用Ajax。

我本来想要做的是:从PHP传递变量以在JS中使用其值设置变量 (例如:var name = "somehow get the the variable from the PHP file";),然后使用img.src = "uploads/" + name;

我希望我已经清楚地解释了我的问题。 任何帮助或提示将不胜感激,谢谢!

以下是不同的代码:

index.html

    <!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="css/index.css" >
    <link rel = "icon" href="logo.png" type="image/x-icon">
</head>

<body>
  <div class="topnav">
    <img src="logo.png" style="width:40px;height:40px;"></img>
    <a class="active" href="index.html">HOME</a>
    <a href="help.html">HELP</a>
    <a href="about.html">ABOUT</a>
    <a href="examples.html">EXAMPLES</a>
  </div>

<div class="dropzone" id="dropzone">
  <img src="" id="img" class="img">
  <form class="form" id="myForm">
    <input type="file" id="inpFile" accept="image/png, image/jpg, image/jpeg" hidden="hidden">
    <button type="button" id="custom">CHOOSE AN IMAGE</button>
    <button type="submit" class="btn" id="btn">START SORTING</button>
</div>
<script src="drop.js" type="text/javascript"></script>
</body>
</html>

drop.js:

const realBtn = document.getElementById("inpFile");
const customBtn = document.getElementById("custom");
const inpFile = document.getElementById("inpFile");
const myForm = document.getElementById("myForm");
var btn = document.getElementById("btn");
btn.disabled = true;

realBtn.onchange = function(e) {
  btn.disabled = false;
}

customBtn.addEventListener("click", function(click) {
  inpFile.click();
});

myForm.addEventListener("submit", e => {
  e.preventDefault();

  const endpoint = "upload.php";
  const formData = new FormData();

  formData.append("inpFile", inpFile.files[0]);

  console.log();

  fetch(endpoint, {
    method: "post",
    body: formData
  }).catch(console.error);

  document.getElementById("btn").style.display = "none";
  document.getElementById("custom").style.display = "none";
  document.getElementById("img").style.display = "block";

  var img = document.getElementById("img");

  var fileName = ???;

  img.src = "uploads/";

}); 

upload.php:

<?php

$uploadOk = 1;
$fileName = $_FILES["inpFile"]["name"];
$fileTmpName = $_FILES["inpFile"]["tmp_name"];
$fileExtsion = explode('.', $fileName);
$fileActualExtension = strtolower(end($fileExtsion));
$fileNewName = uniqid('').'.'.$fileActualExtsion;
$targetPath = "uploads/" . basename($fileNewName);


if ($_FILES["inpFile"]["size"] > 500000000) {
    $uploadOk = 0;
}

if ($uploadOk == 1) {
    move_uploaded_file($fileTmpName, $targetPath);
}

?>

1 个答案:

答案 0 :(得分:2)

upload.php 中,您可以返回$fileNewName值以将其作为响应发送:

<?php

$uploadOk = 1;
$fileName = $_FILES["inpFile"]["name"];
$fileTmpName = $_FILES["inpFile"]["tmp_name"];
$fileExtsion = explode('.', $fileName);
$fileActualExtension = strtolower(end($fileExtsion));
$fileNewName = uniqid('').'.'.$fileActualExtsion;
$targetPath = "uploads/" . basename($fileNewName);


if ($_FILES["inpFile"]["size"] > 500000000) {
    $uploadOk = 0;
}

if ($uploadOk == 1) {
    move_uploaded_file($fileTmpName, $targetPath);
}

echo json_encode($fileNewName);

?>

然后在fetch()响应中获取它:

myForm.addEventListener("submit", e => {
  e.preventDefault();

  const endpoint = "upload.php";
  const formData = new FormData();

  formData.append("inpFile", inpFile.files[0]);

  console.log();

  var fileName;
  fetch(endpoint, {
    method: "post",
    body: formData,
    headers : { 
        'Content-Type': 'application/json',
        'Accept': 'application/json'
    }
  })
  .then(function (response) {
      return response.json()
  })
  .then(function (data) {
      fileName = data;
  })
  .catch(console.error);

  document.getElementById("btn").style.display = "none";
  document.getElementById("custom").style.display = "none";
  document.getElementById("img").style.display = "block";

  var img = document.getElementById("img");


  img.src = "uploads/";

});