gpt4 book ai didi

javascript - 如何从 javascript 警报调用 php 函数

转载 作者:行者123 更新时间:2023-12-03 08:51:01 25 4
gpt4 key购买 nike

基本上我想做的是 - 创建一个页面来上传文件。下面是代码及其工作正常:

    <!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function wow_default_alert() {alert("Successfully saved!"); }
</script>
</head>
<body>

<form action="index.php" method="post" name="myForm" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>

<?php

if(isset($_POST["submit"])) {
if (!file_exists('.\\tigerimg\\'))
{
mkdir('.\\tigerimg\\', 0777, true);
}
$target_dir = '.\\tigerimg\\';
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image


$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
"File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
"File is not an image.";
$uploadOk = 0;
}

// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file))
{
// echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
echo '<script type="text/javascript">
wow_default_alert();
</script>';
} else {
echo "Sorry, there was an error uploading your file.";
}
}
}
?>

但问题是,如果我在成功上传一个文件后再次刷新页面,它会使用相同的帖子值。

之前我使用下面的代码来取消设置帖子数据 - 这适用于其他页面。

清除代码 1

    <?php
session_start();

if( strcasecmp($_SERVER['REQUEST_METHOD'],"POST") === 0)
{
$_SESSION['postdata'] = $_POST;
header("Location: ".$_SERVER['PHP_SELF']."?".$_SERVER['QUERY_STRING']);
exit;
}

if( isset($_SESSION['postdata']))
{
$_POST = $_SESSION['postdata'];
unset($_SESSION['postdata']);
}
?>

但我不能在这个中使用它。显示错误:

Undefined index: fileToUpload in C:\xampp\htdocs\up\index.php on line 41
Notice: Undefined index: fileToUpload in C:\xampp\htdocs\up\index.php on line 47
Warning: getimagesize(): Filename cannot be empty in C:\xampp\htdocs\up\index.php on line 47
Notice: Undefined index: fileToUpload in C:\xampp\htdocs\up\index.php on line 62

因此,我也尝试通过使用上述代码添加 3 行来清除 FILES 数组。

清除代码 2

    <?php
session_start();

if( strcasecmp($_SERVER['REQUEST_METHOD'],"POST") === 0)
{
$_SESSION['postdata'] = $_POST;
$_SESSION['filedata'] = $_FILES; //new code
header("Location: ".$_SERVER['PHP_SELF']."?".$_SERVER['QUERY_STRING']);
exit;
}

if( isset($_SESSION['postdata']))
{
$_POST = $_SESSION['postdata'];
$_FILES = $_SESSION['filedata']; //new

unset($_SESSION['postdata']);
unset($_SESSION['filedata']); //new
}
?>

但现在它只显示一个错误:

Warning: getimagesize(C:\xampp\tmp\php1A2F.tmp): failed to open stream: No such file or directory in C:\xampp\htdocs\up\index.php on line 51.

>>> 那么,这里有一个问题 - 为什么会发生这种情况?

好吧,现在我尝试了另一种方法,将上面的 [clear Code-1] 放入 php 函数 remove_post() 中,并在成功上传的代码之后调用它 - 我在其中调用了警报.

这次工作正常了。但现在的问题是警报没有出现。那么,当用户点击alert中的ok时,是否可以调用函数remove_post()。

最佳答案

您似乎正在尝试从 W3Schools 网站复制,这不是最好的地方。无论如何,在这种情况下,我认为您可能希望在页面顶部进行所有处理,如下所示:

<?php
// Not sure if you are storing anything in sessions...
session_start();
// Create a root
define("ROOT_DIR",__DIR__);
// Create a function so you can customize it if you want to
function SaveFileToDisk($dir = '/tigeimg/',$allow = array("image/png","image/jpeg","image/gif"))
{
// Make directory if not exists
if(!is_dir($mkdir = ROOT_DIR.$dir)) {
if(!mkdir($mkdir,0755,true))
return 'mkdir';
}
// Filter filename
$name = preg_replace("/[^0-9a-zA-Z\.\_\-]/","",$_FILES["fileToUpload"]["name"]);
// Assign name
$filename = (!empty($name))? $name : false;
// If empty, record error
if(!$filename)
$error[] = 'nofile';
// Get mime type
$mime = (!empty($_FILES["fileToUpload"]["tmp_name"]))? getimagesize($_FILES["fileToUpload"]["tmp_name"]) : false;
// Record if invalid
if(!$mime)
$error[] = 'invalid';
// Filter out double forward slashes (if user decides to change $dir)
// and adds too many forward slashes
$final = str_replace("//","/",ROOT_DIR."/".$dir."/".$filename);
// If file exists, record error
if(is_file($final))
$error[] = 'exists';
// If too big record error
if($filename > 500000)
$error[] = 'size';
// If not in the allowed file types, record error
if(!in_array($_FILES["fileToUpload"]["type"],$allow))
$error[] = 'type';
// Return array of errors
if(!empty($error))
return $error;
// True or false if no errors are recorded previously
return (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"],$final));
}

// Just create a simple error returning function
// This is expandable by adding error descriptions stored in database if desired
function ErrorReporting($value = false)
{
$msg['invalid'] = "INVALID File!";
$msg['type'] = "The file you are trying to upload is not a valid image type.";
$msg['exists'] = "The file you are trying to upload is already uploaded.";
$msg['size'] = "The file you are trying to upload is too large.";
$msg['nofile'] = "The file you are trying to upload has no name.";

if($value === true)
return "Successfully uploaded!";
elseif(is_array($value)) {
foreach($value as $error) {
$err[] = (!empty($msg[$error]))? $msg[$error]:"";
}

if(!empty($err))
return implode("",$err);
}
else
return "File failed to upload.";
}

// If post is submitted
if(isset($_POST["submit"]))
// Run the uploader function
$success = SaveFileToDisk();

?><!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
<?php
// if there is an upload, run the js alert
if(isset($success)) {
?>
function error_alert(errmsg)
{
alert(errmsg);
}

error_alert("<?php echo ErrorReporting($success); ?>");
<?php }
?>
</script>
</head>
<body>

<form action="" method="post" name="myForm" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>

关于javascript - 如何从 javascript 警报调用 php 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32671094/

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