简体   繁体   English

使用JavaScript修改PHP会话变量

[英]Modifying PHP Session Variables with JavaScript

I have some implicit PHP functions which are to be called on particular front-end events; 我有一些隐式PHP函数,可以在特定的前端事件上调用这些函数; such as button onclick s. 例如button onclick s。 By doing so this should modify my PHP SESSION variable accordingly. 这样,应该相应地修改我的PHP SESSION变量。 However, both functions, setAlan() and setMark() , seem to be getting called even if I just want the first one to execute. 但是,即使我只希望第一个函数执行,两个函数setAlan()setMark()似乎都被调用了。

<?php
    session_start();

    function setAlan() {
        $_SESSION['passed_user']='alan';
    }
    function setMark() {
        $_SESSION['passed_user']='mark';
    }
?>

<script>
    function getAlan() { $(document.body).append('<?php setAlan(); ?>'); }
    function getMark() { $(document.body).append('<?php setMark(); ?>'); }
    function show() { alert(' <?php echo "{$_SESSION['passed_user']}" ?> '); }
</script>

<div class="pod">
    <div class="pod_title"><h2>Select a User</h2></div>
    <div>
        <input type="button" onclick="getAlan();" value="alan">
        <input type="button" onclick="getMark();" value="mark">
        <input type="button" onclick="show();" value="show">
    </div>
</div>

I don't understand why setMark() is being called automatically? 我不明白为什么setMark()被自动调用? By what I've written, I believe I am only defining the PHP functions, not calling them; 通过我写的内容,我相信我只是在定义PHP函数,而不是在调用它们。 I use JS for that. 我为此使用JS。 Am I missing something? 我想念什么吗? Thanks in advance! 提前致谢!

PHP is executed first, server side. PHP首先在服务器端执行。 Once PHP is done, your browser ( client ) gets the result, Javascript is executed on the client, so after PHP is done. PHP完成后,您的浏览器(客户端)将得到结果,在客户端上执行Javascript,因此在PHP完成之后。

You can't mix javascript and PHP as you did with: 您不能像下面那样混合使用javascript和PHP:

<script>
  function getAlan() { $(document.body).append('<?php setAlan(); ?>'); }
  function getMark() { $(document.body).append('<?php setMark(); ?>'); }
  function show() { alert(' <?php echo "{$_SESSION['passed_user']}" ?> '); }
</script>

However you can use Javascript to call some server side PHP script with ajax ( Asynchronous JavaScript and XML ). 但是,您可以使用Javascript用ajax(异步JavaScript和XML)调用某些服务器端PHP脚本。

http://www.w3schools.com/ajax/default.ASP http://www.w3schools.com/ajax/default.ASP

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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