我使用ajax在sql中更新img
为什么不按 sweetalert 按钮页面就刷新了?
sweetalert显示一段时间后,网页会立即自动刷新,无需按sweetalert按钮。
但是当尝试更新非图像数据时代码可以正常工作。
阿贾克斯:
function handleSubmitimgForm(formId) {
let form = $(formId);
let formUrl = form.attr("action");
let reqMethod = form.attr("method");
let formData = new FormData(form[0]);
$.ajax({
url: formUrl,
type: reqMethod,
data: formData,
processData: false,
contentType: false,
success: function(data) {
let result = JSON.parse(data);
if (result.status == "success") {
console.log("Success", result);
Swal.fire("Success!", result.msg, result.status).then(function() {
window.location.reload();
});
} else {
console.log("Error", result);
Swal.fire("Error!", result.msg, result.status);
}
}
});
}
PHP:
session_start();
require_once "db.php";
$user_id = $_POST['uid'];
$img = $_FILES['img'];
$img2 = $_POST['img2'];
$upload = $_FILES['img']['name'];
if ($upload != '') {
$allow = array('jpg', 'jpeg', 'png');
$extension = explode('.', $img['name']);
$fileActExt = strtolower(end($extension));
$fileNew = rand() . "." . $fileActExt;
$filePath = '../../uploads/' . $fileNew;
if (in_array($fileActExt, $allow)) {
if ($img['size'] > 0 && $img['error'] == 0) {
move_uploaded_file($img['tmp_name'], $filePath);
}
} else {
$fileNew = $img2;
}
try {
$stmt = $conn->prepare("UPDATE users SET img = ? WHERE user_id = ?");
$stmt->execute([$fileNew, $user_id]);
echo json_encode(array("status" => "success", "msg" => "Successfully"));
} catch (PDOException $e) {
echo json_encode(array("status" => "error", "msg" => "Something went wrong"));
}
}
我已经使用了preventDefault(),但它仍然会自动刷新。但我已经修好了。问题来自于我使用的是五台服务器。