我在插入了USB温度探测器的服务器上对PHP脚本进行了简单的ajax调用。当温度超过100时,ajax调用不会始终返回适当的温度。有时它返回完整的温度(即145.78),有时它只返回超过100的部分(即45.78)。
从命令行运行PHP脚本每次都会产生一致的结果;无论我连续多少次运行它。
我创建了另一个PHP文件,只是让它回显123.45并通过ajax调用运行它,它似乎一致地返回完整的数字。
以下是与此相关的示例代码:
JS
function monitorLoop() {
$.ajax({
url: 'temp0.php',
type: 'get',
dataType: 'html',
success: function(data) {
console.log( data );
}
});
}
$("#toggleMonitor").on( "click", function() {
looping = !looping;
if (looping) {
loop = setInterval( function() { monitorLoop(); }, 1000 );
} else {
clearInterval( loop );
}
});
PHP
<?php
$pattern = '/[0-9]*[0-9][0-9]\.[0-9][0-9]/';
$temperature = exec('sudo pcsensor -f -n0');
preg_match( $pattern, $temperature, $output, PREG_OFFSET_CAPTURE);
echo $output[0][0];
?>
这是控制台和命令行的输出:
控制台
"90.74" brewery.js:47
"90.29" brewery.js:47
"90.29" brewery.js:47
"89.39" brewery.js:47
"89.39" brewery.js:47
"89.39" brewery.js:47
"89.39" brewery.js:47
"89.39" brewery.js:47
"89.39" brewery.js:47
"89.61" brewery.js:47
命令行
190.29pi@raspberrypi /var/www $ php temp0.php
190.40pi@raspberrypi /var/www $ php temp0.php
190.85pi@raspberrypi /var/www $ php temp0.php
191.08pi@raspberrypi /var/www $ php temp0.php
190.96pi@raspberrypi /var/www $ php temp0.php
190.29pi@raspberrypi /var/www $ php temp0.php
190.62pi@raspberrypi /var/www $ php temp0.php
190.18pi@raspberrypi /var/www $ php temp0.php
189.61pi@raspberrypi /var/www $ php temp0.php
189.39pi@raspberrypi /var/www $ php temp0.php
当我将间隔从1000毫秒减慢到2000或甚至3000毫秒时似乎好一点,但它仍然不一致。我上面发布的运行是将间隔设置为2000,并且它从未显示整数。