在重定向到 PHP 页面后显示使用 JavaScript 的消息

showing messages using javascript after redirecting to a php page

本文关键字:JavaScript 消息 显示 重定向 PHP      更新时间:2023-09-26

我正在处理一个联系页面。它使用Slim 3框架进行重定向。一切都很好,但我想添加一些jQuery代码来通知用户电子邮件是否已发送。这是我的PHP代码:

<?php
require 'vendor/autoload.php';
$app = new Slim'App();
//... slim views codes
$app->get('/', function ($req, $res, $args) {
    return $this->view->render($res, "about.twig");
})->setName('home');

$app->get('/contact', function ($req, $res, $args) {
    return $this->view->render($res, "contact.twig");
})->setName('contact');

$app->post('/contact', function ($request, $response, $args){
    $body = $this->request->getParsedBody();
    $name = $body['name'];
    $email = $body['email'];
    $msg = $body['msg'];
    if(!empty($name) && !empty($email) && !empty($msg) ){
        $cleanName  = filter_var($name,FILTER_SANITIZE_STRING);
        $cleanEmail = filter_var($email,FILTER_SANITIZE_EMAIL);
        $cleanMsg   = filter_var($msg,FILTER_SANITIZE_STRING);
    }else {
        $path = $this->get('router')->pathFor('contact');
        return $response->withRedirect($path);
        // javascript: please fill the fields.
    }
    //sending mail
    ]);
    $result=$mailer->send($message);
    if ($result > 0) {
        // javascript: your email has been sent
        $path = $this->get('router')->pathFor('home');
        return $response->withRedirect($path);
    } else {
        // javascript: error sending mail
        $path = $this->get('router')->pathFor('contact');
        return $response->withRedirect($path);
    }
});
$app->run();

如您所见,基本上有两个页面:"联系人"和"主页"。联系页面中有一个表单,如果表单提交成功并发送电子邮件,页面将被重定向到"主页",但如果没有,它将再次重定向到"联系"。现在我想添加jQuery代码,以便我可以判断用户电子邮件是否已发送。我的 HTML 中有这样的东西:

<div id="feedback" class="success">
  <h3>Success!</h3>
  <p>You're email has been sent.</p>
</div>

在我的 js 文件中:

$(document).ready(function() {
    $(".success").click(function() {
        $("#feedback").addClass("dismissed");
    });
});

多谢!

$message = "Your text";
echo "<script type='text/javascript'>alert('$message');</script>";