简体   繁体   中英

How do I include Javascript inside PHP?

I'm trying to write some Javascript inside PHP, I made a simple button that takes you to the previous page. The button is showing but the functionality of the button isn't working. This is the code I have.

<?php
$product;
if (empty($product))
{
    echo
    '
    <script>
    function myFunction() {
        header("location:".history.go(-1));
    }
    </script>
    <button onclick=myFunction()>Click me</button>
    ';
    exit();


}

I go to my local server to the file where this code is and except it to work but it doesn't. For example, I go to http://127.0.0.1/test1.php where there is is a button (which works perfectly) that takes you to http://127.0.0.1/test2.php (where this this piece of code is). When I press the 'Click me' button, nothing happens. I'm wondering what I'm doing wrong? Or is it because It's local that the problems are caused? I've tried this in Chrome and Safari.

You have wrong code history:

function myFunction() {
    window.history.go(-1);
}

You only have to close your PHP part before you start with javascript like this: ?> . After the JS part, open PHP again with <?php . In this way you can also use HTML inside PHP.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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