简体   繁体   English

php vars正在更新,但javascript函数始终显示第一个值

[英]php vars are updating but javascript function shows allways first value

I have a php class that set values and updates them. 我有一个设置值并更新它们的php类。 I use getters methods to access those varibles from a javascript function and show them in screen. 我使用getters方法从javascript函数访问这些变量,并在屏幕上显示它们。 My problem is when I launch that javascript code, my vars are shown allways with the first values they get. 我的问题是,当我启动该javascript代码时,我的var始终以它们获得的第一个值显示。 I've checked them and they are up to date when I call myCreateFunction(); 我已经检查了它们,当我调用myCreateFunction();时它们是最新的myCreateFunction(); but is like this function launches before the php vars are updated. 但是就像此功能在更新php vars之前启动。 I'm new in javascript and some help would be appreciated, thanks! 我是javascript新手,感谢您的帮助!

<?php    
    class TableRows {

        public $offerId = 0;

        public function setOfferId(){
            $this->offerId ++;
        }
        public function getOfferId(){
            $this->offerId;
        }

    }

    $tb = new TableRows(); 
?>
<script>
    function myCreateFunction(string) {
        var offerId =  '<tr><th>'+<?php echo json_encode($tb->getOfferId()); ?>+'</th></tr>';
        var table = document.getElementById("myTable");
        var row = table.insertRow(-1);
        var cell1 = row.insertCell(0);
        cell1.innerHTML = offerId;
    }
</script>
<script>
    myCreateFunction();
</script>
<?php
    $tb->setOfferId();
?>
<script>
    myCreateFunction()
</script>

You have some problem in understanding where you are in your code (in javascript or in php). 您在理解代码中的位置(使用javascript或php)时遇到了一些问题。 $tb->setOfferId(); does not modify anything in your javascript. 不会修改您的JavaScript中的任何内容。 So the second call to myCreateFunction() will be exactly the same. 因此,对myCreateFunction()的第二次调用将完全相同。

Yes, because myCreateFunction is being rendered by your browser on your second call. 是的,因为您的浏览器在第二次调用时呈现了myCreateFunction PHP (server-side) has nothing in common with JavaScript (client-side). PHP(服务器端)与JavaScript(客户端)没有任何共同点。 Don't mix your code like that. 不要像这样混合您的代码。

Instead, you can use setters, getters, and then pass the value to your JavaScript function as parameter. 而是可以使用setter,getter,然后将值作为参数传递给JavaScript函数。

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

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