How to print JavaScript with PHP

前端 未结 3 1623
半阙折子戏
半阙折子戏 2021-01-25 23:44

I need to pass some JS variable to PHP and am having some trouble.

I have tried the following:

$product_id = \"

        
3条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-26 00:25

    By doing it your way, it's just impossible. PHP can't "read" or "interact with" javascript directly in the same page.

    You have to understand that PHP is a preprocessor, it generates HTML on the server, then the generated page is sent to the client. In this page, the PHP code has entirely disappeared. You can only see what it generated (that is, HTML or JS). Then, the javascript code runs, and it has no idea it was generated using PHP, and no idea of PHP's presence whatsoever.

    In order to pass variables to a PHP script, you have to call the file with GET or POST methods :

    (JS)

    $.get( 'myScript.php', { // This is calling the PHP file, passing variables (use get or post)
         variable1 : "Hello",
         variable2 : "world!"
       }, function(data){ // PHP will then send back the response as "data"
          alert(data); // will alert "Hello world!"
    });
    

    (myScript.php)

        $variable1 = $_GET['variable1']; // or POST if you're using post
        $variable2 = $_GET['variable2'];
    
        echo $variable1 . " " . $variable2; // Concatenates as "Hello world!" and prints it out.
    //The result of the PHP file is sent back to Javascript when it's done.
    

    Of course, this is a very basic example. Never read and use directly what is sent to PHP (as I just did), because anyone could inject whatever they'd want. Add securities.

提交回复
热议问题