我在我的主HTML页面Smartmeter.html中有一个javascript代码,通过它我显示每5秒更改一次的仪表数据。
现在我需要每30秒通过php将这个在javascript函数中被更改的仪表数据插入到mysql中。
意味着我需要留在Smartmeter.html页面上,因为javascript函数正在执行5s,同时还会每30秒将这个仪表数据(变量 - 目标)插入到mysql中。
我怎样才能做到这一点?有人可以帮我提供一些代码或建议。
我的Smartmeter.html页面:
<html>
<head></head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript">
window.onload=dynamic;
var target=100;
function dynamic()
{
var1=Math.random();
target=target + var1 * 1000;
target=Math.round(target);
if(target>123457)
{
target=15647;
}
document.getElementById('hidden').value = target;
func();
}
function func()
{
//configuration of the reading displayed
var primary = document.getElementById("d").getElementsByClassName("imge")[0].getElementsByTagName("h2")[0];
primary.innerHTML=target;
alert('test');
document.forms["myForm"].submit();
// window.location.href = "http://localhost/SUA/Data_insertion.php?target=" + target;
setTimeout(dynamic, 5000);
}
</script>
<body>
<style>
.imge
{
position: absolute;
top: 40%;
left: 30%;
margin-top: -150px;
margin-left: -150px;
}
h2{
position: absolute;
top: 116px;
left: 165px;
width: 100%;
}
p
{
position: absolute;
top: 120px;
left: 250px;
width: 100%;
}
input {
display: inline-block;
float: bottom;
}
</style>
<body bgcolor="#BDBDBD">
<form action="Data_insertion.php" method="post" id="myForm">
<input type="hidden" id="hidden" name="reading" value=""><br>
<input type="submit" value="submit">
</form>
<div id="d">
<div class="imge">
<img src="meter.jpg" width="450" height="350" alt="" />
<h2>1234578 </h2>
<p><font size="5">kWh</font></p>
</div>
</div>
</body>
</html>
答案 0 :(得分:0)
jQuery的解决方案:
function submitValue(url, key, value){
$.ajax({
type: "POST",
url: url,
data: {
key: key,
value: value
},
success: function(data){
alert("done: "+data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Error');
}
});
}
像这样处理您的数据:
<?php
switch($_POST['key']){
case "voltage": setVoltage($_POST['value']); break;
case "current": setCurrent($_POST['value']); break;
default: http_response_code(404); die() break;
}
echo "successful set ".$_POST['key']." to ".$_POST['value'];
function setVoltage($voltage){
/* sql magic */
}
function setCurrent($current){
/* sql magic */
}
?>
修改强>
对于您的问题,这个简单的版本应该有效:
function sendValue(){
$.ajax({
type: 'POST',
url: 'Data_insertion.php',
data: {
reading: target
},
success: function(data){
alert('done');
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Error');
}
});
}
function init(){
// remove this line from function func()
setTimeout(dynamic, 5000);
setTimeout(sendValue, 30000);
}
和更改
<body bgcolor="#BDBDBD">
<form action="Data_insertion.php" method="post" id="myForm">
<input type="hidden" id="hidden" name="reading" value=""><br>
<input type="submit" value="submit">
</form>
到
<body bgcolor="#BDBDBD" onLoad="init()">
<button onClick="sendValue(target)">Submit</button>