在成功上传文件时显示 Javascript alert()


display Javascript alert() upon successful upload of a file

我有一个小型上传系统来上传个人资料图片。我想显示一个带有 1 个按钮的警报框(已成功上传)。这是我的PHP上传功能:

function change_profile_image($user_id, $file_temp, $file_extn){
    $file_path = substr(md5(time()), 0, 10) . '.' . $file_extn;
    move_uploaded_file($file_temp, 'images/profile/'.$file_path);
    Thumbnail('images/profile/', $file_path, 'images/thumbs/');
    mysql_query("UPDATE `users` SET `profile` = 'images/profile/" . mysql_real_escape_string($file_path) . "' WHERE `user_id` = " . (int)$user_id);
}

以下是我调用该函数的方式:

if (in_array($file_extn, $allowed) === true) {
                        change_profile_image($session_user_id, $file_temp, $file_extn);
                        header('Location: ' . $current_file);
                        exit();
                    }

这可能是jQuery的工作。实际上,可能是这样

但是一个可能接近的第二个(也是更简单的)选项可能是传递一个GET参数作为确认:

header("Location: {$current_file}?loaded=ok");

然后在"当前文件"中检查它,也许在正文的末尾:

if (isset($_GET['loaded'])) {
    if ('ok' == $_GET['loaded'])
        $msg = "Loaded OK!";
    else
        $msg = "Oh noes! Error {$_GET['loaded']} while updating picture";
    // Remember, keep $msg without 'quote' "signs", or '"escape'" them properly
    print <<<DISPLAY_ALERT
<script>
    alert('$msg');
</script>
DISPLAY_ALERT;
}

注意:上面的代码使用PHP"这里文档"。它们的工作原理是这样的:字符串由<<<SOMESEQUENCE引入,SOMESEQUENCE之后你不能有任何内容。并且由仅包含 SOMESEQUENCE;单行终止,任何地方都没有多余的空格。即使是单个空间的存在也会导致有时难以诊断的故障。此外,YOUR_SEQUENCE在 PHP 代码中必须是唯一的。您不能有两个具有相同顺序的 heredoc(在紧要关头,将它们编号:SEQUENCE1SEQUENCE2 )。

在 heredoc 中,您可以使用不带引号的字符串和回车符,因此当我无法使用正确的模板时,这是我最喜欢的包含 HTML 片段的方式。