将多个PHP文件的请求合并为一个请求
问题描述:
我有一个动态的网页仪表板,显示温度,湿度,光线,噪音等数据。我有多个php文件,如temp.php,humidity.php,light.php和noise .php负责从db中检索数据,然后我也有多个js文件,它们基本上都使用setTimeout,并且每隔3秒将相应php文件的数据显示到html页面。将多个PHP文件的请求合并为一个请求
每个PHP文件看起来像这样,例 - humidity.php:
<?php
session_start();
if(isset($_SESSION["user_id"])){
include('db.php');
$unit = "820";
$stmt = $db->prepare("SELECT hv FROM humidity where
unitid=? order BY pk DESC LIMIT 1");
$stmt->execute([$unit]);
$humidity= $stmt->fetchColumn();
$humidity=round($humidity, 2, PHP_ROUND_HALF_ODD);
echo $humidity;
$stmt->closeCursor();
$db = null;
}
?>
而且每个JS文件看起来像这样,例 - humidity.js:
$(document).ready(function() {
function foo() {
$('#showhumidity').load('humidity.php');
setTimeout(foo, 3000);
}
foo();
});
的过程工作正常,但由于有多个PHP请求,整体处理时间很短(大约2秒)。我想将phps结合到一个php文件中,并将js文件合并为一个 - 因此只需一个php请求就可以检索所有数据。
这样做的最佳方法是什么?
答
希望下面的方法会帮助你。
在合并后的PHP文件:
<?php
$humidity = getHumidity(<parameter>);
$temp = getTemp(<parameter>);
$light = getLight(<parameter>);
$retArr = array("humidity" => $humidity,"light" => $light, "temp" => $temp);
echo json_encode($retArr);
function getHumidity($param) {
// write your logic here to calculate the humidity
}
function getTemp($param) {
// write your logic here to calculate the temp
}
function getLight($param) {
// write your logic here to calculate the Light
}
?>
在你的单身.js文件:
jQuery(document).ready(function() {
function foo() {
jQuery.ajax({
url : <path of your php file>,
type : <Method GET/POST as per your requirement >,
dataType : json,
async : false,
success : function(data, status) {
//update your html element with data
},
}
setInterval(foo, 3000);
});
2秒调用PHP 3文件只是读取数据库中的值?我怀疑,合并这些文件会改善任何事情,因为问题似乎是别的...... – dognose