2014-03-29 88 views
0

我想實現投票系統,並有一個while循環顯示數據庫中的投票結果。剛開始的時候,我試着回顯id作爲投票向上按鈕的值,然後通過ajax請求獲取按鈕的id顯示。請求正在通過,但無論點擊哪個按鈕,它都會提供相同的ID。我在表格中有4行,當我看到源頁面時,我可以正確看到每個按鈕的值,它是1-4,但是當我點擊按鈕時,它只返回最後一個4(我正在訂購DESC)。有人可以幫忙嗎?ajax響應返回相同的值

<div class="response"></div>  

while($row = $result->fetch_assoc()) 
    { 
    echo"<button value='".$row['id']."' class='btn btn-default test' href='javascript:void(0);' onclick='voteup();'>."$row['voteup']".</button>"; 
    } 

JS

function voteup() 
{ 
var dataString = 'test='+ test; 
     $.ajax({ 
     type: "GET", 
     url: "test.php?tar=vrate", 
     data: dataString, 
     cache: false, 
     success: function(response) 
     { 
      $(".response").fadeIn('slow').html(response); 

     } 
     }); 
} 

test.php的

if(isset($_POST["tar"]) && !empty($_POST["tar"]) || isset($_GET["tar"]) && !empty($_GET["tar"])) 
{ 
if(isset($_GET["tar"]) == "vrate")  
{ 
$cos = $_GET['test']; 
echo $cos; 
} 
} 
+0

你知道'isset'返回一個布爾值,告訴你它是否被設置,所以比較它與字符串可能沒有什麼意義嗎? – adeneo

+0

你不會將$ row ['id']傳遞給test.php! –

+0

我希望'fetch-assoc()'是一個錯字 –

回答

1

這個代碼可以使用一些幫助,所以這裏有一些指針和一個答案:

保持清晰分離php和html通過使用替代while語法。

按鈕沒有href。我刪除了onclick,所以它會附加在jquery中。

<div class="response"></div>  

<?php while($row = $result->fetch_assoc()): ?> 
    <button value='<?=$row['id']?>' class='btn btn-default test'> 
    <?=$row['voteup']?> 
    </button> 
<?php endwhile; ?> 

JS

$(function() { 
    $('.test').on('click', function() { // attach the click to the button 
    var test_val = $(this).val(); // Grab the value from the button 
    $.ajax({ 
     type: "GET", 
     url: "test.php", // Move ?tar=vrate to the data array. 
     data: {tar: 'vrate', test: test_val}, 
     cache: false, 
     success: function(response) 
     { 
      $(".response").fadeIn('slow').html(response); 

     } 
    }); 
    }); 
}); 

test.php的

既然你正在做一個GET請求,$ _ POST不應該有任何那裏。一次只能設置$ _GET和$ _POST中的一個。您無法同時執行這兩種類型的請求。

空測試不是必需的,因爲無論如何您只是在檢查某個值。

if(isset($_GET["tar"]) && $_GET["tar"] == "vrate") 
{ 
    $cos = $_GET['test']; 
    echo $cos; 
} 
+0

謝謝你現在工作。 – user3412305