How can I echo JS redirection?

前端 未结 1 854
北恋
北恋 2021-01-25 23:30

I want to echo a javascript mobile device redirection to the mobile site.
But I have to give an \'id\' with the redirect link. This is my code as of now:

<         


        
相关标签:
1条回答
  • 2021-01-26 00:25

    JS and PHP are two different animals and they do not mix together the way you are using those presently, which explains the syntax errors you are getting, because you are declaring what PHP thinks are constants.

    • http://php.net/manual/en/function.constant.php

    What you need to do is to seperate those.

    First, the JS/HTML:

    <!DOCTYPE html>
    
    <head>
       <title></title>
    </head>
    
    <body>
        <script type="text/javascript">
    
        <!--
        if (screen.width <= 800) {
           window.location = "redirection_page.php?set=true";
        }
    
        else {
           document.write ("Show them a message, or do something else.");
        }
        //-->
        </script>
    
    </body>
    </html>
    

    Then the PHP: (redirection_page.php)

    <?php
    
    if(isset($_GET['set']) && $_GET['set'] == true ){
    
    header("Location: http://www.example.com/");
    
    exit;
    
    }
    

    So, in your case that would read something like this:

    N.B.: (You will need to do some modifications as to what the GET array will be).

    <!DOCTYPE html>
    
    <head>
       <title></title>
    </head>
    
    <body>
    
    <?php 
    
    $_GET['id'] = 2;
    
    ?>
    
        <script type="text/javascript">
    
        <!--
        if (screen.width <= 800) {
           window.location = "mplayer.php?id=<?php echo $_GET['id'] ?>";
        }
    
        else {
    
           document.write ("Show them a message, or do something else.");
    
        }
    
        //-->
        </script>
    
    </body>
    
    </html>
    

    PHP: (mplayer.php)

    <?php
    
    if(isset($_GET['id']) && $_GET['id'] == 2 ){
    
       echo $id = $_GET['id'];
    
    }
    

    Also make sure that you are not outputting before header (this means no HTML above the PHP, a space before the <?php tag, a cookie, etc. If this doesn't work for you, then your system may not be set to catch/display errors/notices/warnings, so enable error reporting.

    If you do see a headers sent notice, read the following on Stack:

    • How to fix "Headers already sent" error in PHP

    Add error reporting to the top of your file(s) which will help find errors.

    <?php 
    error_reporting(E_ALL);
    ini_set('display_errors', 1);
    
    // rest of your code
    

    Sidenote: Displaying errors should only be done in staging, and never production.

    0 讨论(0)
提交回复
热议问题