如何在 <script> 标签内使用 PHP 变量

Dev*_*vTN 1 javascript php jquery

我在 URL 中传递 PHP 变量,所以我的页面链接如下所示www.example.com?redirect=neworders

根据$_GET['redirect']值,我在示例中创建页面内容input

然后在这一<script>部分中,我想根据PHP值调用带有参数的函数。

我当前的代码现在可以工作,但我相信这不是应该完成的正确方法,尽管我检查了多个线程并且通常答案是我提到的选项之一。

如果我做对了,有什么建议吗?我在代码中添加了注释以了解我的情况。非常感谢。

    <?php 
    
   //my url can be either www.example.com?redirect=neworders or www.example.com?redirect=deliveredorders

    switch($_GET['redirect']) {
      case 'neworders':
          $page = 'Backlog'; 
          break;
      case 'deliveredorders':  
          $page = 'Shipment';   
          break;
          }
    
    ?>
    
      <body>
    //based on $page value, I create the input value with a specific id
    <?php  
    if ( $page == 'neworders') { 
     echo '<input type="text" id="BacklogName" placeholder="enter order number">'; }
    elseif ( $page == 'deliveredorders') { 
     echo '<input type="text id="ShipmentName" placeholder="enter order number then serial number">'; 
    } 
    ?> 
    
    <button type="button" id="submitButton">Submit</button>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    
      </body>
    
    <script>
    $(document).ready(function() { 
    
      //I have some functions declared here to use based on $page value

    function submitEvent(element, input) {
    element.click(function() {      
      alert(input.val());
      }); 
    }
    
    //based on $page value, intialize the function with exact selectors
    
    //first Option came to my mind : check the $page value and echo function intialization as string
    <?php 
    if ( $page == 'neworders') { 
      echo 'submitEvent($("#submitButton"), $("#BacklogName"));'; }
    elseif ( $page == 'deliveredorders') { 
      echo 'submitEvent($("#submitButton"), $("#ShipmentName"));'; } 
    ?> 
    
    //second option came to my mind : use javascript 'if else' and only echo the $page value
    
    if ("<?php echo $page; ?>" == "neworders") { 
      submitEvent($("#submitButton"), $("#BacklogName")); }
    else if ("<?php echo $page; ?>" == "deliveredorders") { 
      submitEvent($("#submitButton"), $("#ShipmentName")); 
    }
    
    });
    </script>
Run Code Online (Sandbox Code Playgroud)

Ham*_*han 5

你可以像这样使用它:

<script type="text/javascript">
  
    var baz = <?php echo 42; ?>;
    alert(baz);
</script>
Run Code Online (Sandbox Code Playgroud)