0

我在 JS 上有这两个功能:

<script>
    function inc(elem)
    {
        elem.value++; 
    }
    function dec(elem)
    {
        if(elem.value>1)
        {
            elem.value--;
        }
    }
</script>

html中的这种形式:

<form method="POST" action= "tameio.php"  >
<input type="hidden" value="0" id="counter" name="counter">
<input type = "submit" value = "NextPage" name = "submit" onClick="inc(document.getElementById('counter')); ">
<input type = "submit" value = "PreviousPage" name = "submit" onClick="dec(document.getElementById('counter'));">
</form>

这是 php :

<?php
if(isset($_POST['submit']))
{
    echo $_POST['counter'];
    if($_POST['submit'] == 'NextPage'){
    ...
        }
}
?>

所以问题是,在我单击 NextPage 按钮后,0 变为 1,但它没有存储在表单中,因此它在 html 上再次变为 0。如果我重新单击它,它将再次发送 1。我应该改用ajax吗?

4

2 回答 2

1

没有必要这样做,

<form method="POST" action= "tameio.php"  >
<input type="hidden" value="<?=$current_page?>" id="counter" name="counter">
<input type = "submit" value = "NextPage" name = "submit" onClick="inc(document.getElementById('counter')); ">
<input type = "submit" value = "PreviousPage" name = "submit" onClick="dec(document.getElementById('counter'));">
</form>

在 PHP 中:

<?php
if(isset($_POST['submit']))
{
    if($_POST['submit'] == 'NextPage')
    {
        $current_page = $_POST['counter'] + 1;
    } else {
        $current_page = $_POST['counter'] - 1;
    }
} else {
    $current_page = 1;
}
// Fetch the page data based on the current page
...

?>>

但我建议您使用 GET 而不是帖子来执行此操作。

<a href="tamieo.php?page=<?=$current_page - 1?>">Previous Page</a> |
<a href="tamieo.php?page=<?=$current_page + 1?>">Next Page</a>

在 PHP 中:

<?php

    if(isset($_GET['page']) && $_GET['page'] > 0)
        $current_page = (int) $_GET['page'];
    else
        $current_page = 1;
于 2013-08-16T11:38:15.410 回答
0

试试这样-

<script>
    function inc(elem)
    {
        document.getElementById('counter').value = elem.value +1; 
    }
    function dec(elem)
    {
        if(elem.value>1)
        {
            document.getElementById('counter').value = elem.value -1;
        }
    }
</script>
于 2013-08-16T11:23:26.187 回答