Jquery load() and PHP variables

前端 未结 6 838
死守一世寂寞
死守一世寂寞 2020-12-03 00:29

If I load a PHP page with Jquery .load(file.php), can the included file use the php variables that were defined on the page that called the load()?

6条回答
  •  自闭症患者
    2020-12-03 00:46

    You're misunderstanding how things work.

    • PHP runs before any browser response is issued to the client, and all code runs on the server. The variables declared in your PHP file are destroyed after all the PHP code has been run; they "vanish."
    • JavaScript runs after the browser response has begun, and all code runs on the client. By "loading" the output result of the PHP file, you won't get any access to PHP's variables, only the output.

    If you want to transfer certain variables from PHP to JavaScript, you could dump some output into JSON in your PHP script, like so:

     $myVariable)));
    
        /* Output looks like this:
           [
               {
                   "myVariable": "hello world"
               }
           ]
        */
    ?>
    

    Your JavaScript/JSON should look something like this:

    $.getJSON("test.php", function(result) {
        console.log(result[0].myVariable);
    });
    

    Does that make sense?

提交回复
热议问题