php - 为了处理表单数据*通过 ajax*,我需要添加到 PHP 文件中的哪些调整
问题描述
我创建了一个收集文件上传的表单。起初,我将表单数据传递给一个 PHP 文件 (action="filename.php"),该文件处理数据并将文件上传到服务器中的专用文件夹,效果很好。唯一困扰我的是,当用户单击“提交”时,它会将他重定向到 PHP 页面,但我希望所有 PHP 进程只能在幕后工作。所以我使用了一个堆栈溢出用户上传到这里的 ajax 代码,这就是问题所在:当我点击“提交”时,我确实收到了成功警报,但是当我进入服务器时 - 我没有看到需要上传到服务器的文件。我认为这是我需要调整的 PHP 过程中的一些东西,因为新的变化
$('.form1').submit(function(e){
e.preventDefault();
var str = $( ".form" ).serialize();
$.ajax({
url: '/Learn/wordpress/wp-content/themes/hello-elementor/upload.php',
type: 'post',
data: $('.form').serialize(),
success:function(){
var number = 4;
alert(number);// Whatever you want to do after the form is successfully submitted
}
});
});
<?php
if (isset($_POST['submit'])) {
$file = $_FILES['file'];
$fileName = $_FILES['file']['name'];
$fileTmpName = $_FILES['file']['tmp_name'];
$fileSize = $_FILES['file']['size'];
$fileError = $_FILES['file']['error'];
$fileType = $_FILES['file']['type'];
$fileExt = explode('.', $fileName);
$fileActualExt = strtolower(end($fileExt));
$allowed = array('jpg', 'jpeg', 'png');
if (in_array($fileActualExt, $allowed)) {
if ($fileError === 0) {
if ($fileSize < 10000000) {
$fileNameNew = uniqid('', true).".".$fileActualExt;
$fileDestination = 'test-uploads/'.$fileNameNew;
move_uploaded_file($fileTmpName, $fileDestination);
} else {
echo "your file is too big!";
}
} else {
echo "There was an error uploading your file!";
}
} else {
echo "you cannot upload file of this type!";
}
}
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<script
src="https://code.jquery.com/jquery-3.5.1.min.js"
integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0="
crossorigin="anonymous"></script>
</head>
<body>
<form class="form1" method="POST" enctype="multipart/form-data">
<input type="file" name="file">
<button type="submit" name="submit">upload</button>
</form>
<script src="upload.js"></script>
</body>
</html>
解决方案
推荐阅读
- python - 使用 SimpleImputer 输入最小值时出错
- python - OLS回归python中的预测形状未对齐错误
- mysql - 选择查询中的 Laravel 雄辩的 json
- message-queue - 消息队列 *like* 技术
- sharing - 将带有 Angular 的 Nativescript 的 Web 和移动代码共享迁移到版本 8
- sql - 如何根据特定类型对表中的行值求和?
- swiftui - List swiftUI中的单选按钮
- gitlab - 我们可以将具有多个元素的 gitlab 变量传递给 shell 脚本吗
- c - 当元素在头尾之间时,在基于平面数组的双链表中搜索
- flutter - Flutter:扩展覆盖 ConstrainedBox