2013-08-16 43 views
0

我對JS的2個功能方面的數據:如何保存的JavaScript形式

<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。我應該用阿賈克斯嗎?

+0

我想你要找的是什麼[會話cookie(http://www.php.net/session)。 – Mike

回答

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; 
+0

注意:未定義的變量:current_page。如果我把它定義爲0上面的某處我仍然得到1 –

+0

PHP應該在HTML之上工作 – Nils

+0

我明白了,現在完成了,不用擔心:) –

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> 
+0

nop,仍然是相同的結果。表格的值仍然重置爲0 –