如何避免在页面刷新时重置Javascript变量?

时间:2016-10-03 18:24:08

标签: javascript php jquery html ajax

我在页面上有一些图像,当点击其中一个图像时,会发送POST数据,刷新页面并增加Javascript变量。我的问题是如何让JS变量不重置为重新加载页面时我启动它的值?我之前也尝试使用localstorage保存变量,但变量仍然被重置 - 这是合乎逻辑的,因为我在同一文档中进行了初始化,但我不知道如何做其他事情。< / p>

我是Javascript的新手,希望尽可能保持简单(如果可能的话,我会得到一个虚拟回复)。

下面是我的代码,在正文的开头有相关的Javascript(在单独的文档中也有一些不相关的php):

<?php
$subtest_nr = "7";
$counter = 0;
require_once('php.php');
?>

<!DOCTYPE html>
<html>
<head>
<title>Title</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<link rel="stylesheet" href="styles.css">
<script src="jquery-3.1.1.min.js"></script>
<script src="scripts.js"></script>
</head>

<body>
<script>
var counter = 0;
$(document).ready(function(){
    $("img").click(function(){
        counter += 4;
        $("#test").text(counter); //for testing
    });
    $("#test").text(counter); //for testing
});

jQuery(function($) {
    // Hide / suppress the submit button
    $('input[type="submit"]').closest('div').hide();
    // Bind to change event for all radio buttons
    $('input[type="radio"]').on('change', function() {
        // Submit the form ("this" refers to the radio button)
        $(this).closest('form').submit();
    });
});
</script>

<div class="main">
    <div id="test"></div>
    <?php $data = getData($subtest_nr); ?>
    <form id="myform" method="post">
    <div class="four_images">
            <div class="flex-item">
                <input type="radio" name="image" value="7.11" id="alt1" class="hidden">
                <label for="alt1"><img src="images/<?php echo $data[$counter+0]; ?>"></label>
            </div>
            <div class="flex-item">
                <input type="radio" name="image" value="7.12" id="alt2" class="hidden">
                <label for="alt2"><img src="images/<?php echo $data[$counter + 1]; ?>"></label>
            </div>
            <div class="flex-item">
                <input type="radio" name="image" value="7.13" id="alt3" class="hidden">
                <label for="alt3"><img src="images/<?php echo $data[$counter+2]; ?>"></label>
            </div>
            <div class="flex-item">
                <input type="radio" name="image" value="7.14" id="alt4" class="hidden">
                <label for="alt4"><img src="images/<?php echo $data[$counter+3]; ?>"></label>
            </div>
            <div>
                <input type="submit" name="save" value="Save Image Selection">
            </div>
    </div>
    </form>
</div>

</body>
</html> 

我可以补充一点,我想保持页面刷新,因为稍后我想将增量变量传递给php,而不必使用Ajax等发布它。 (希望这会让我作为初学者变得更简单。)

2 个答案:

答案 0 :(得分:1)

您可以在执行post请求之前将变量存储到localStorage中,并在页面加载时从localStorage读取计数器变量。 localStorage Browser Support

或者您可以将计数器变量作为URL参数发送,并通过PHP设置计数器。

答案 1 :(得分:1)

这是一个非常基本的例子,说明如何使用localStorage并设置简单的会话getter / setter来操作页面刷新数据。

function setSessionItem(name, value) {
    var mySession;
    try {
        mySession = JSON.parse(localStorage.getItem('mySession'));
    } catch (e) {
        console.log(e);
        mySession = {};
    }

    mySession[name] = value;

    mySession = JSON.stringify(mySession);

    localStorage.setItem('mySession', mySession);
}

function getSessionItem(name) {
    var mySession = localStroage.getItem('mySession');
    if (mySession) {
        try {
            mySession = JSON.stringify(mySession);
            return mySession[name];
        } catch (e) {
            console.log(e);
        }
    }
}

function restoreSession(data) {
    for (var x in data) {
        //use saved data to set values as needed
        console.log(x, data[x]);
    }
}



window.addEventListener('load', function(e) {
    var mySession = localStorage.getItem('mySession');
    if (mySession) {
        try {
            mySession = JSON.parse(localStorage.getItem('mySession'));
        } catch (e) {
            console.log(e);
            mySession = {};
        }
        restoreSession(mySession);
    } else {
        localStorage.setItem('mySession', '{}');
    }

    setSessionItem('foo', Date.now()); //should change each time

    if (!mySession.bar) {
        setSessionItem('bar', Date.now()); //should not change on refresh
    }
}, false);