2016-09-25 63 views
0

我一直在試圖讓這個腳本正常工作。我製作了一個PHP隨機數生成器,我試圖將它提供給我的主php頁面,並使用每次按下按鈕時生成的數字更新div。使用PHP/Javascript更新元素

它工作,種。它會生成第一個數字,無論您之後按下按鈕多少次,它都不會再更新該元素。

我以爲我可能必須先清除元素,所以我添加了它,但它仍然無法工作。下面是我的index.php和randomRoller.php

<?php 
include("./includes/randomRoller.php") 
?> 
<style type="text/css"> 
#cookies { 
    width: 50px; 
    height: 100px; 
    background-color: #000000; 
    color: #ffffff; 
} 
#bunnies { 
    width: 100px; 
    height: 500px; 
    background-color: #555555; 
    color: red; 
} 
</style> 
<script> 
function roll() { 
    document.getElementById('bunnies').innerHTML = ''; 
    document.getElementById('bunnies').innerHTML = '<?php echo(roll()) ?>'; 
} 
</script> 
<button type="button" onClick="roll()">Test</button> 
<div id="cookies"> 
</div> 
<br> 
<br> 
<div id="bunnies"> 
</div> 

./includes/randomRoller.php

<?php 
    function roll() { 
     return rand(1 , 200); 
    } 
?> 

任何提示或建議,您可以給我將不勝感激代碼。

+0

打開生成的html,看看你有什麼有 –

+0

的[客戶端和服務器端編程之間的區別是什麼?]可能的複製(HTTP://計算器.COM /問題/ 13840429 /什麼,是最差的客戶間-SI de-and-server-side-programming) –

+0

它會產生一次性的原因,因爲您的頁面中只有一個調用roll()。每次按下按鈕,使用ajax獲取新的隨機數 – Andreas

回答

0

我不知道這是否是至關重要的,它是產生數一個單獨的頁面,如果沒有可以用JS創建一個隨機數,像這樣:

<script> 
function roll() { 
    var bunnies = document.getElementById('bunnies') 
    bunnies.innerHTML = Math.floor((Math.random() * 10) + 1); 
} 
</script> 
<button type="button" onClick="roll()">Test</button> 

您可以使用AJAX(jQuery的庫)從另一個頁面加載號:

function roll() { 
    $.get("/includes/randomRoller.php", function(data) { 
    $("#bunnies").html(data); 
    }); 
}