2017-04-12 154 views
-1

我有這個variable.php其中包含一個變量:刷新變量

<?php 
// Start the session 
session_start(); 
?> 
<html> 

<head> 

<link rel="stylesheet" href="style.css"/> 

<body> 

<div> 

<?php 


$output = shell_exec("sh r.sh"); 

$op = preg_split("#[\r\n]+#",trim($output)); 

$rest = substr("$op[0]",-5); 

$value= hexdec($rest); 

$value=$value/1000; 

?> 
<?php 
$_SESSION["value1"] = "$value"; 
?> 

</div> 

</body> 

</head> 

</html> 

和我有這個index.php頁面,其顯示我的變量值:

<?php 
session_start(); 
?> 
<html> 

<head> 

<link rel="stylesheet" href="style.css"/> 

<body> 
<?php print $_SESSION["value1"] ; ?>       

</body> 

</head> 

</html> 

我怎樣才能使用Jquery從variable.php中刷新變量$ value並在index.php中每1秒刷新一次?

我嘗試這樣做:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 

 
<script> 
 

 
setTimeout("location.reload(true)",1000); 
 

 
</script>

但它只是刷新的index.php,但不是variable.php

感謝。

+0

你好,歡迎來到Stackoverflow。我們在這裏幫助您解決特定的編程問題,而不是爲您編寫代碼。告訴我們你試過的東西,與我們分享你的想法,我們會提供幫助,但沒有人會爲你寫代碼。首先,你的變量.php中不需要所有'html'標籤,你不會顯示任何內容。 – Twinfriends

+0

我試圖這樣: 但它刷新index.php每1秒,但不是變量。 – Zekeriya

回答

0

只是讓你variable.php做到這一點:

<?php 
    // Start the session 
    session_start(); 

    $output = shell_exec("sh r.sh"); 
    $op = preg_split("#[\r\n]+#",trim($output)); 
    $rest = substr("$op[0]",-5); 
    $value= hexdec($rest); 
    $value=$value/1000; 

    $_SESSION["value1"] = $value; 

在你index.php做到這一點:

<?php 
    require_once('variable.php'); 
?> 
<html> 
<head> 
</head> 
<body> 
    <?php echo $_SESSION["value1"]; ?> 
    <script> 
     setTimeout(function(){ 
      window.location.reload(1); 
     }, 1000); 
    </script> 
</body> 
</html> 

這將在variable.php每次運行代碼index.php被加載。 JavaScript使頁面每秒重新加載一次。

通過對更新變量並返回變量的PHP頁面進行AJAX調用,也可以使其更加優雅。如果你想使用AJAX和jQuery閱讀這篇文章:https://api.jquery.com/jquery.get/

+0

它工作得很好,但事實是我只是想要更新變量。我會把一些圖像在PHP中,所以每秒都會刷新圖像,這就是我不想... – Zekeriya

+0

@Zekeriya然後,你將不得不看看我的答案的AJAX/jQuery部分:-)。良好的閱讀。 – Jogge

+0

我已經閱讀過這篇文章,但我不明白它對我有什麼好處? – Zekeriya

0

也許你可以使用Ajax的工作,在這裏我把一個例子:

這是你的index.html

<!DOCTYPE html> 
    <html> 
    <head> 
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> 
    </head> 
    <body> 
    <p id="demo"></p> 

    <script type="text/javascript"> 

    function myFunction() { 
     $.ajax({ url: 'test.php', 
      data: {action: 'test'}, 
      type: 'post', 
      success: function(output) { 
       document.getElementById("demo").innerHTML = output; 
       setInterval(myFunction(), 500); 
         } 
      }); 


    } 
    setInterval(myFunction(), 500); 

    </script> 
    </body> 
    </html> 

,爲此例如,你可以使用一個PHP這樣 test.php的

<?php echo date("Y-m-d H:i:s"); ?> 

你可以改變其他文本test.php的結果,但如果你把此行中我瘦k它會更清楚你