如何在javascript中使用PHP变量值

How to use PHP variable value in javascript?

本文关键字:PHP 变量值 javascript      更新时间:2023-09-26

我的web应用程序使用PHP、HTML和Javascript。现在,我对以下代码有一个小问题。

$e=$_POST['users']; //$e should have either employee_id or a string "All"

现在,根据这个值,我必须将HTML按钮重定向到特定的页面。就我而言,

if $e=="employee_id(or may be you could say that $e!="All")" then redirect the page to salary_report.php

if $e=="All" then the page should redirect to salary_report_combined.php

我当前的按钮代码如下:

<input type="button"  class="btn btn-primary" id="leavere" name="leavere" value="Back to Salary Report" onclick="location.replace('salary_report.php')"></input> 

所以目前它只重定向到salary_report.php文件。我的问题是,我应该如何应用基于PHP变量值的条件并执行HTML代码?现在你能帮我解决这个问题吗。提前知道。

您可以这样做:

if($e == "All"){
$redirectTo = "salary_report_combined.php";
}
else{
$redirectTo = "salary_report.php";
}

在您的按钮中:

<input type="button"  class="btn btn-primary" id="leavere" name="leavere" 
value="Back to Salary Report" onclick="location.replace('<?php echo $redirectTo ?>')"></input>

但我只想创建一个重定向页面为href的链接,如下所示:

<a href="<?php echo $redirectTo; ?>"> Back to Salary Report </a>

希望这能有所帮助!

您还可以使用以下内容:

var $e = <?php echo $_POST['users'] ?>;

然后在条件中使用$e

作为问题的解决方案,您可以将重定向url存储到php变量中,然后访问javascript代码片段中php变量的值。

E.g

 <?php
 $redirection_url='';   //Initialzing of variable for redirection url
 if($e=='All')
 {
     $redirection_url='salery_report_combined.php';
 }
 else
 {
      $redirection_url='salary_report.php';
 }
 ?>
    <input type="button"  class="btn btn-primary" id="leavere" name="leavere" value="Back to Salary Report" onclick="window.location.replace('<?php echo $redirection_url; ?>')"></input>