我正在嘗試爲Raspberry Pi製作一個簡單的Web GUI。 它應該使用PHP和JavaScript在圖像上繪製溫度值。從javascript調用PHP函數
我將在PHP和我正在編寫的C++應用程序之間使用一些IPC。但現在我只想從文件中讀取一個值並將其繪製在圖像上。 (該文件是使用OWFS一個1-Wire總線的溫度值)
我的問題
JavaScript函數ReadTemps()獲取每5秒調用,但PHP值僅被更新時,頁面刷新。
我的問題沒有JavaScript的使用經驗。
代碼
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<title>Still life web application</title>
<canvas id="myCanvas" width="768" height="576" style="border:0px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
<?php
function get_temp()
{
echo round(floatval(file_get_contents('/mnt/1wire/uncached/vessel/temperature')), 2);
}
?>
<script>
var bgImg = new Image();
bgImg.src = 'image.jpg';
function ReadTemps()
{
var vessel_temp = '<?php get_vessel_temp(); ?>';
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.drawImage(bgImg, 0, 0);
ctx.font="20px Georgia";
ctx.fillText(vessel_temp + '\u00B0', 330, 430);
setTimeout(ReadTemps, 5000);
}
window.onload = ReadTemps;
</script>
</head>
<body>
<a href="javascript:ReadTemps();">Update</a>
</body>
</html>
如果我在ReadTemps
添加警報( 「你好」),它會彈出每隔5秒。
解決方案
<script>
var bgImg = new Image();
stillImg.src = 'image.jpg';
function ReadTemps()
{
var vessel_temp = loadXMLDoc('get_vessel.php');
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.drawImage(bgImg, 0, 0);
ctx.font="20px Georgia";
ctx.fillText(vessel_temp + '\u00B0', 330, 430);
setTimeout(ReadTemps, 5000);
}
function loadXMLDoc(file)
{
var xmlhttp;
if(window.XMLHttpRequest)
xmlhttp = new XMLHttpRequest();
else
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.open("GET", file, false);
xmlhttp.send(null);
if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
return xmlhttp.responseText;
else
return "error";
}
window.onload = ReadTemps;
</script>
誰會拿這個? :) 好的。 這是因爲每次重新加載頁面只生成一次,所以您的vessel_temp值只在頁面生成時定義 - 您必須使用稱爲AJAX的東西。對不起,但我沒有更多時間向你解釋這一點。 –
@TK先生我想我明白了。 將檢查出AJAX。 – John
請參閱[此問題](http://stackoverflow.com/q/4542863/1267304)。是ajax網絡上數以千計的例子之一。 – DontVoteMeDown