douyanlu7380 2017-02-16 13:26
浏览 55
已采纳

在javascript中从数据库更新JSON

Aim: User clicks a button it retrieves latest record of json from database and updates state of green led to 1

Here whats I have so far, all code in one file index.php

The php code

$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;
}

Then html

<a href="#" class="btn btn-default" onclick="myFunction()">More Options</a>

Then 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>

Both console.log produces the same thing...

"{"smartdevices":[{"device":"greenled", "state":"0"},{"device":"redled", "state":"1"}]}"

Is it because in my javascript im trying to loop through something that isn't yet in the right state to be looped like this?

Thanks in advance

console.log ( emparray );

  • 写回答

1条回答 默认 最新

  • doushang4293 2017-02-16 13:37
    关注

    The content from your database is a string. You need to decode the string first so your entire PHP array is evaluated when you run json_encode.

    First, alter your PHP code like this:

    //create an array
    $emparray = array();
    while($row =mysqli_fetch_assoc($result))
    {
        // Decode the string here
        $emparray[] = json_decode($row['json']);
    }
    

    You now need to loop the outer array, then the code inside.

    Something like this:

    // 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;
            }
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?