目的:用户单击一个按钮,从数据库中检索json的最新记录,并将绿色状态更新为1
到目前为止,这里我所拥有的一切,所有代码都在一个文件中index.php
php代码
$sql = "SELECT json FROM `smartlight` ORDER BY timestamp desc limit 1";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
//create an array
$emparray = array();
while($row =mysqli_fetch_assoc($result))
{
$emparray[] = $row;
}
然后html
<a href="#" class="btn btn-default" onclick="myFunction()">More Options</a>
然后用javascript
<script type="text/javascript">
function myFunction(){
var emparray = <?php echo json_encode($emparray) ?>;
console.log ( emparray );
for (var i=0; i<emparray.length; i++) {
if (emparray[i].device == "greenled") {
emparray[i].state= "1";
break;
}
}
console.log ( emparray );
}
</script>
两个console.log都会产生相同的结果...
"{"smartdevices":[{"device":"greenled", "state":"0"},{"device":"redled", "state":"1"}]}"
是因为在我的JavaScript代码中,我试图通过某种尚未处于正确状态的循环来循环吗?
提前致谢
数据库中的内容是一个字符串。您需要先对字符串进行解码,以便在运行时对整个PHP数组进行求值json_encode
。
首先,如下更改您的PHP代码:
//create an array
$emparray = array();
while($row =mysqli_fetch_assoc($result))
{
// Decode the string here
$emparray[] = json_decode($row['json']);
}
现在,您需要循环外部数组,然后循环内部代码。
像这样的东西:
// Loop the outer array (each part of $row)
for (var i = 0; i < emparray.length; i++) {
// Loop each part of the 'smartdevices' array
for (var j = 0; j < emparray[i]['smartdevices'].length; j++) {
if (emparray[i]['smartdevices'][j]['device'] == "greenled") {
emparray[i]['smartdevices'][j]['state'] = "1";
break;
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句