gpt4 book ai didi

php - Ajax 成功函数不会对响应使用react

转载 作者:行者123 更新时间:2023-12-01 07:42:34 25 4
gpt4 key购买 nike

我制作了一个照片上传系统,但现在遇到了问题:

这里是 Ajax 部分:

$(document).ready(function(){
$("#upload").click(function(e){
var formData = new FormData(this);
e.preventDefault();
e.stopPropagation();
$.ajax({
type: "POST",
url: "../system/avatar_system.php",
data:formData,
cache:false,
contentType: false,
processData: false,
success: function(data){
if(data == "upload_ok"){
location.reload();
}
},
error: function(){
}
});
});
});

这里是 html:

<div class="form_box">
<form id="avatar_form" enctype="multipart/form-data" method="post" action="../system/avatar_system.php">
<input type="file" accept="image/*" id="file" name="file" class="select_file">
<label for="file">Bild auswählen</label>
<input id="upload" type="submit" value="Bild ändern" class="upload_file">
</form>
</div>

这里是 avatar_system.php:

if(isset($_FILES['file'])){
$dirpath = "../users/". $username ."/avataruploads/";
if(!is_dir($dirpath)){
if(!mkdir($dirpath, 0777, true)){
$error = error_get_last();
echo "Failed creating Folder";
exit();
}
}

$file = $_FILES['file'];

$fileName = $_FILES['file']['name'];
$fileType = $_FILES['file']['type'];
$fileTmpName = $_FILES['file']['tmp_name'];
$fileSize = $_FILES['file']['size'];
$fileError = $_FILES['file']['error'];

$fileExplode = explode('.', $fileName);
$fileExt = strtolower(end($fileExplode));

$allowed = array('jpg', 'jpeg', 'png', 'gif');
if(in_array($fileExt, $allowed)){
if($fileError === 0){
if($fileSize < 32768000){
$fileNewName = uniqid('', true) . '.' . $fileExt;
$filepath = $dirpath . $fileNewName;
move_uploaded_file($fileTmpName, $filepath);
$sql = "UPDATE users SET avatar = '$filepath' WHERE username = '$username'";
mysqli_query($conn, $sql);
mysqli_close($conn);
echo "upload_ok";
exit();
}else{
echo "This file is to big";
exit();
}
}else{
echo "There was an Error";
exit();
}
}else{
echo "Not allowed Extension";
exit();
}
}

如果响应为“upload_ok”,我希望网站重新加载,但我收到一个新的空白页面,其中包含消息“upload_ok”。或者也许它不应该重新加载页面,而只是立即更改头像。

这怎么可能?

最佳答案

正如您在错误文本中看到的那样

TypeError: Argument 1 ('form') to the FormData constructor must be an instance of HTMLFormElement

您传递至 FormData <form>但是<input[type=submit]> .

所以,你应该传递 <form> 。最简单的方法是

var formData = new FormData(this.form);

这是可能的,因为 inputform永远拥有属性(property)form ,其中有 <form> ,该输入属于。

关于php - Ajax 成功函数不会对响应使用react,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45350064/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com