繁体   English   中英

如何将 PHP 变量传递给外部 javascript 文件

[英]How to pass a PHP variable to an external javascript file

请原谅我的菜鸟问题,如果您决定提供帮助,我需要一个菜鸟可以真正理解的答案。 我有 php 脚本,它通过 php 邮件 function 发送电子邮件。 正确发送电子邮件后,我希望能够将变量传递给位于我的网站文件夹中的 app.js 文件。 这是我的 php 脚本:

        $mail->send();
        $alert = '<div class="sentMessage active">
                    <i class="far fa-times-circle"></i>
                    <p>Thank you! Your message was successfully sent.</p>
                  </div>';
        header('Location: index.php');
    } catch (Exception $e){
       $alert = '<div class="alert-error">
                    <span>'.$e->getMessage().'</span>
                    </div>';
    }
}

现在不是让 php 像上面的脚本那样创建 div,我只希望它向我的 javascript 发送一个真或假,以便我可以控制在我的 javascript 中发生的事情。

我怎样才能做到这一点?

如何让我的 app.js 知道我的 php 脚本中发生了什么? 再次为菜鸟问题感到抱歉!

由于您想通知用户邮件成功,您可以在查询参数中发送一个名为mailSent的变量,该变量将是 boolean

$mail->send();
      $alert = '<div class="sentMessage active">
                <i class="far fa-times-circle"></i>
                <p>Thank you! Your message was successfully sent.</p>
                </div>';
       header('Location: index.php?mailSent=true'); // note the mailSent param
} catch (Exception $e){
   $alert = '<div class="alert-error">
                <span>'.$e->getMessage().'</span>
                </div>';
}

在您的 app.js 文件中,您可以访问查询参数,这取决于您使用的框架

对于香草 JS,您可以使用

const urlParams = new URLSearchParams(window.location.search);
const myParam = urlParams.get('mailSent'); // mailSent: true then show a successful alert or something 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM