【问题标题】:How to pass Variable from list by button press [closed]如何通过按钮从列表中传递变量[关闭]
【发布时间】:2021-05-01 21:46:23
【问题描述】:

我的目标是读取目录,将项目添加到列表中,添加单个按钮以删除文件,然后添加代码以删除所选文件。删除不是问题,但传递文件是。

这是我尝试过的:

<?php

 if ($handle = opendir('userStorage/Storage1')) {
   while (false !== ($file = readdir($handle)))
      {
          if ($file != "." && $file != "..")
      {
            $filelocation = "userStorage/Storage1/$file";
            $thelist .= '<p1>'.$file.'</p1><form method="post">
            <button>Download</button>
            <button type="submit" name="delete'.$file.'" value="Submit" >Delete</button><br></form>';
          }
       }
  closedir($handle);
  }       
?>

<?php
if($_POST["delete'.$file.'"] == "Submit" ) {
    
        echo "File to be deleted: $file";
    }
  ?>

【问题讨论】:

  • 您希望通过$_POST["delete'.$file.'"] 获得什么?这只是一个值,当您在循环中构建表时,n 有不同的值。您需要重新构建 HTML。你是如何触发删除操作的?是常规的表单提交还是 AJAX?
  • 请说明您遇到的问题。

标签: php html file


【解决方案1】:

试试这个

<?php

if (isset($_POST['delete'])) {
    unlink(__DIR__ . DIRECTORY_SEPARATOR . $_POST['file']);
}

if (isset($_POST['download'])) {
    header('Location: ' . $_POST['file']);
}

$files = array_diff(scandir(__DIR__), ['..', '.']);

foreach ($files as $file) {
    echo "
        <p>{$file}</p>
        <form action='' method='POST'>
            <input type='hidden' name='file' value='{$file}'>
            <input type='submit' name='download' value='Download'>
            <input type='submit' name='delete' value='Delete'>
        </form>
    ";
}

【讨论】:

  • 您只需要添加一个 hidden 类型的输入并为其命名 $file 然后您就可以使用 $_POST 获取值
  • 您好,效果很好,谢谢,恭喜您第一次回答!
  • 感谢您很高兴看到它对您有所帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-15
  • 2018-11-05
  • 2022-07-13
相关资源
最近更新 更多