首页 > 解决方案 > 如何通过单击调用 php 文件来处理上传的文件

问题描述

我是 javascript 和 php 初学者,我已经尝试了 2 天的解决方案,这可能很容易,但我找不到任何解决方案。所以,我的 index.php 带有一个文件输入和一个按钮,我希望当用户单击该按钮时,它会执行一个 js 函数,该函数将调用我的 excelparse.php 文件来处理上传的文件,但我不知道我是如何可以在函数上调用excelparse.php文件。如何在 on.click 函数上调用 excelparse.php 文件?

    //index.php
    <form>
<div class="form-group">
    <label for="ficheiro">Select a file</label>
    <input type="file" class="form-control-file" id="ficheiro">
</div>
<button type="button" id="parse" class="btn btn-light">Parse</button>
</form>

    //js.js
    parse.on("click", function() {

    });

    //excelparse.php
    $path_parts = pathinfo($_FILES["file"]["name"]);
    $extension = $path_parts['extension'];
    if ($extension == 'xls') {
        $extension = 'Xls';
    }
    elseif ($extension == 'xlsx') {
        $extension = 'Xlsx';
    }

    move_uploaded_file($_FILES['file']['tmp_name'],('files/tmp'));

    $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($extension);
    $spreadsheet = $reader->load("files/tmp");
    $sheet = $spreadsheet->getActiveSheet();        
    foreach ($sheet ->getRowIterator() as $row) {
        $cellIterator = $row ->getCellIterator();
        $cellIterator->setIterateOnlyExistingCells(false);
        $array = array();
        foreach ($cellIterator as $cell) {
            if (!is_null($cell)) {
                $value = $cell->getFormattedValue();
                $array[] = $value;                                        
            }                
        }
        print_r($array);
    }

标签: javascriptphpjquery

解决方案


您不能像 Javascript 一样在 HTML 文件中执行 PHP 命令。

PHP 是一种服务器端语言,它将在服务器中执行并将响应推送到客户端。

这里需要用到在javascriptAJAX中调用a (jQuery很简单)。URL (your php file)

jQuery Ajax 请求

一个简单的 jQuery Ajax 请求就像,

    function callPhp() {

      $.ajax({
        url: "http://server.com/yourPhpFileUrl.php"
      }).done(function() {
         alert(0);
      });

   }

在您的代码中

您可以使用表单提交方法提交文件,

<form action='http://server.com/yourPhpFileUrl.php' method='post' enctype='multipart/form-data>

否则

您还可以使用 AJAX 请求发送文件

使用 Ajax 上传文件


推荐阅读