简体   繁体   English

JavaScript中的PHP变量未更新

[英]PHP variable in JavaScript is not getting updated

I'm trying to pass a PHP variable (number) to JavaScript. 我正在尝试将PHP变量(数字)传递给JavaScript。 It kind of works but as soon as the number changes, it's not getting updated. 可行,但是一旦数字更改,它就不会更新。 My code: 我的代码:

    $totalamount = $woocommerce->cart->get_total(); 
    $totalamount = preg_replace("/[^0-9\.]/", "", $totalamount);
    $totalamount = number_format($totalamount, 2, '.', '');
    var_dump($totalamount);
?>

<script type="text/javascript">
    var Amount = "<?php echo $totalamount; ?>"

In the var_dump($totalamount); var_dump($totalamount); the number get's updated every time. 号码每次都会更新。 In JavaScript it gives 0 after a change. 在JavaScript中,更改后该0

What is the proper way to pass a variable to JavaScript so it gets updated? 将变量传递给JavaScript以便进行更新的正确方法是什么?

PHP is a server side language which means it is only executed at the time the page is loading, and the code will not be re-run unless you refresh the page. PHP是一种服务器端语言,这意味着它仅在页面加载时执行,并且除非刷新页面,否则代码不会重新运行。

To get around this you can retrive the total using an AJAX call which would get the total in the background and then update the page. 为了解决这个问题,您可以使用AJAX调用检索总计,这将在后台获得总计,然后更新页面。

To get started with Ajax here is a good tutorial: Ajax 要开始使用Ajax,这里有一个很好的教程: Ajax

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

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