簡體   English   中英

如何從JavaScript警報中調用PHP函數

[英]How to call a php function from javascript alert

基本上我想做的是-創建一個頁面來上傳文件。 以下是代碼及其正常工作:

    <!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.";
                }
            }
        }
    ?>

但是問題是,如果我再次刷新頁面-成功上傳一個文件后,它可以使用相同的發布值。

以前,我使用下面的代碼來取消設置發布數據-適用於其他頁面。

清除Code-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函數function remove_post()中,並在成功上傳代碼之后調用它-在這里我稱為警報。

這次工作正常。 但是現在的問題是警報沒有出現。 因此,當用戶單擊警報中的確定時,是否可以調用函數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>

用戶單擊“確定”以發出警報后,您可以將php函數調用為

alert('Your alert');
document.write(' <?php remove_post(); ?> ');

用戶在警報上單擊“確定”后,將調用您的remove_post()函數

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM