简体   繁体   English

如何在JavaScript中使用PHP变量值?

[英]How to use PHP variable value in javascript?

I'm using PHP, HTML and Javascript for my web app. 我的Web应用程序使用的是PHP,HTML和Javascript。 Now I'm having a small issue with the following code. 现在,以下代码有一个小问题。

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

Now depending on this value I've to redirect a HTML button to a specific page. 现在,根据此值,我必须将HTML按钮重定向到特定页面。 In my case 就我而言

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

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

My current button code is as follows : 我当前的按钮代码如下:

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

So currently it is redirecting to salary_report.php file only. 因此,当前它仅重定向到Salary_report.php文件。 My issue is how should I apply a condition based on PHP variable value and execute the HTML code? 我的问题是我应该如何基于PHP变量值应用条件并执行HTML代码? Now could you help me in resolveing ithis issue. 现在,您可以帮助我解决ithis问题。 Thnks in advance. 提前感谢。

You can do this: 你可以这样做:

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

In your button: 在您的按钮中:

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

But I'd just create a link with the redirect page as href , like so: 但是我只需要创建一个带有重定向页面的链接,如href ,就像这样:

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

Hope this helps! 希望这可以帮助!

You can also use as below: 您还可以如下使用:

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

then use $e in condition. 然后使用$ e作为条件。

As a solution to your problem you can store redirection url into a php variable and then access the value of php variable within javascript code snippet. 为了解决您的问题,您可以将重定向网址存储到php变量中,然后在javascript代码段内访问php变量的值。

Eg 例如

 <?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> 

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

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