简体   繁体   中英

How exactly does PHP execution work and how does it's position in web page affect output?

I was messing around with php to better understand it's execution. I found that when this same code is run with the php block placed at the end of the page, it produces a different output. Can somebody explain it to me. This difference made me go crazy for days when I was working on my mini project.

<?php
    if(isset($_POST["btn1"])){  
        echo "btn1";
        die();
    }   
?>
<html>
    <body>
        <button id="btn1" name="btn1">btn1</button>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <script>
            $(document).ready(function(){
                $("#btn1").click(function(){
                    $.ajax({
                        type:'post',
                        url:'',
                        data:{'btn1':true},
                        datatype:'text',
                        success:function(val){
                            alert(val);
                        }
                    });
                });
            });
        </script>
    </body>
</html>

PS. This code when run as is, produces the proper output ie it alerts "Hello". But when the php code is written at the end, it alerts the html code of the whole page...

PHP is processed inline unless it is wrapped in a function call, a class declaration, or a control statement since it is intended to be included within html. PHP = PHP Hypertext Preprocessor. http://php.net/manual/en/intro-whatis.php I repeat, PHP is processed inline. The server does not load a file and run only the PHP or the HTML, it starts at the beginning of the file and processes the entire file unless there is a function call, class declaration, or some other control statement.

When your initial page loads as written, the 'btn1' parameter hasn't been posted so the if statement is skipped and the server continues executing the page to return the html in the rest of the doc.

When your ajax call reaches the page, it starts at the top and this time the if statement is true because btn1 is set. The die() call tells the server to just quit going through the rest of the page so you get "btn1" from the echo statement.

If you remove the die statement, you'll get the "btn1" text and then the rest of the page from the ajax call. If you put the php block at the end of the page, you'll get the whole page and then the "btn1" text. If you shove that php clock into the middle of the html, the ajax call will return the page with "btn1" in the middle where the code is.

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