尝试使用此代码将URL中的JSON数据解析为html

时间:2015-01-20 22:28:47

标签: javascript php html json

我已经写了这段代码(可能有点乱)。我试图从URL读取JSON数据并以html格式显示(现在简单,更好一点)

这就是我所拥有的。它没有用。



<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>JSON Sample</title>
</head>
<body>
    <div id="placeholder"></div>
    <script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
    <script>
    var jsonApi = "http://10.0.0.2/~nrgtar/test.php?query=64"
	$.getJSON(jsonApi, function(data) {
        var output="<ul>";
        for (var i in jsonApi.results) {
            output+="<li>" + data.results[i].name + " " + data.results[i].lastname + "--" + data.results[i].address+"</li>";
        }

        output+="</ul>";
        document.getElementById("placeholder").innerHTML=output;
  });
    </script>
</body>
</html>
&#13;
&#13;
&#13;

示例JSON数据如下所示:

{
    "results": [
        {
            "name": "John",
            "lastname":"Smith",
            "address":"4 main street"
        }
    ]
}

1 个答案:

答案 0 :(得分:-2)

&#13;
&#13;
<?php

$url = "http://10.0.0.2/~nrgstar/test.php?query=4";
$content = file_get_contents($url);
$json = json_decode($content, true);

foreach($json['results'] as $item) {
print "name " . $item['name'] . " last name " . $item['lastname'] . " address " . $item['address'] . "<br>";
}
?>
&#13;
&#13;
&#13;