如何在每次刷新时将前一个值增加新值

时间:2017-10-31 04:42:51

标签: javascript php jquery

我想在网页刷新时使用新值添加现有值。  我有两个文件,分别是html和php文件。 php文件将显示10到100之间的随机数。而html文件执行get jquery以从php脚本获取数据。然后在网页刷新后,现有值必须增加新值。 例如,

the first value on the webpage is 24.
after refreshing the page, the new value is 89 from the php script
the value on the webpage must be 113 (24+89). 

我将向您展示以下代码。

showtotal.php

<?php


$random = rand(10,100);
echo $random;
?>

showtotal.html

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
 updateFromServer();
    var intervalID = window.setInterval(updateFromServer, 500);

    function updateFromServer() {
        $.get({
            url: 'showtotal.php',
            dataType: 'text',
            success: totalAttacks
        });
    }

    function totalAttacks(val) {
        $('#result').html('Events Today' + val);
    }
</script>
<h1 id="result"></h1>
</body>
</html>

我的代码在每次刷新时显示不同的值。如何通过新值增加现有值?请帮我 。谢谢

3 个答案:

答案 0 :(得分:1)

您可以使用cookiessessionStoragelocalStorage来存储最新值。对于cookie,您可以通过PHP文件获取它,因此在您的Javascript文件中,您只需要调用PHP文件。

答案 1 :(得分:0)

您可以将旧值放在PHP会话中并在PHP端进行此计算,如下所示:

<?php
session_start();
if(!isset($_SESSION['old_value']))
    $_SESSION['old_value'] = 0;
$random = $_SESSION['old_value'] + rand(10,100);
$_SESSION['old_value'] = $random;
echo $random;
?>

答案 2 :(得分:0)

您可以将以前的值存储在隐藏字段中。

function totalAttacks(val) {
    var pre_val = parseInt($('#prev').val());
    var new_val = pre_val+parseInt(val);
    $('#result').html('Events Today' + new_val);
    $('#prev').val(new_val);
}

同时将此添加到yr html

<input type="hidden" id="prev" value="0">