将json_encode($ data)转换为div的仅数据列表的最简单方法

I am new to json_encode.


  • A data.php from another function already exist and produces json_encode($data)

  • json_encode($data) hold only names and sizes from "SELECT name,size FROM lists";

  • window.onload = function ()
    (function () {
    var a = document.getElementById('myDiv');
    if (a) { //*Need list*// }});


Is there a way to extract the json_encode($data) into a list form like: NAME (SIZE) ; one name/size per row for the window.onload function above?

I have wasted to much time with this and would love a solution but am going to code another page list.php to run onload to fill div. Seriously want to know at this point for future knowledge.

JSON:

[{"name":"Cheese Burger","size":"100"}, 
 {"name":"miles","size":"51"},
 {"name":"Halloweens","size":"20"}]

Div will look like:

Cheese Burger (100)
milessize (51)
Halloweens (20)


Normally I would code:

<?php
$query  = "SELECT * FROM lists";
$result = mysql_query($query);
while($row = mysql_fetch_array($result, MYSQL_ASSOC)){?>

<li><?php echo $row['name'] . " (" . $row['size']. ") "; ?></li>

<?php } ?>

But I do not understand to full functionality of json and attempting to add to my knowledge base.
So how would I attain the same result using JSON?

If I understand you well this is what you want:

window.onload = function() {
    var a = document.getElementById("mydiv");
    var hr = new XMLHttpRequest();
    hr.open("GET", "data.php", true);
    hr.setRequestHeader("Content-type", "application/json");
    hr.onreadystatechange = function() {
        if(hr.readyState == 4 && hr.status == 200) {
        var data = JSON.parse(hr.responseText);
      //var data = [{"name":"Cheese Burger","size":"100"}, 
      //            {"name":"miles","size":"51"},
      //            {"name":"Halloweens","size":"20"}];
        a.innerHTML = "";       
        var html='';
        for (var i in data) {
            html +=  data[i].name + "("+ data[i].size +") <br />";
        }
    a.innerHTML=html; 
        }
    }
    hr.send(null);
}

it Will output in your div <div id="mydiv" name="">:

Cheese Burger(100) 
miles(51) 
Halloweens(20) 
// var json comes from php
function convert(json){
    var obj={};
    for(var ii=0;ii<json.length;ii++){
        obj[json[ii].name]=json[ii].size;
    };
    return obj;
}

You would call this function with the data that came from json_encode on the PHP end.