javascript - 如何通过单击调用 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);
}
解决方案
您不能像 Javascript 一样在 HTML 文件中执行 PHP 命令。
PHP 是一种服务器端语言,它将在服务器中执行并将响应推送到客户端。
这里需要用到在javascriptAJAX
中调用a (jQuery很简单)。URL (your php file)
一个简单的 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 请求发送文件
推荐阅读
- scenekit - ARKit:再现项目点功能
- ios - 从 RTMP 流 ios 播放 aac 音频
- linux - X11/XCB/Xlib:复制根窗口到像素图
- angularjs - 如何使用 angular1.6 检查 URL 参数?
- python - Pandas:将滚动统计信息添加到所有列的数据框中
- vuejs2 - vuex store getter 在组件中不起作用
- php - PHP 的 strcasecmp 行为异常
- vuejs2 - 带有日期选择器输入的 V 模型
- python - 用于一维数组或列表的隔离森林 Sklearn 以及如何调整超参数
- python - 如何使用 asyncio 作为模块的一部分来设置后台进程