0

教自己从 mySQL -> PHP -> JSON / Javascript 的数据流,并在这一点上卡住了。我要做的就是遍历外部 JSON 数据并将它们放入无序列表中。我试图编辑 jQuery 网站上给出的示例来为我工作,但我无法弄清楚。任何帮助表示赞赏。这是我的代码。

<script type="text/javascript" src="jquery-1.7.2.min.js"></script>

<script type="text/javascript">
$.getJSON('links.json', function(json) {
// alert("JSON Data: " + json[1].pagetitle);
});

我可以通过使用注释掉的警报来确认数据是从外部 JSON 文件中提取的。

这是我创建 JSON 文件的代码:

// Require Database Connection
require_once "pdo_testdb_connect.php";

// Query Database for all available links
$STH = $dbh->query('SELECT pagetitle, pagelink FROM links');

// If empty..
if ($STH == '') {
echo "There are no links available at this time.";
}

// Set Fetch Mode
$STH->setFetchMode(PDO::FETCH_ASSOC);

$allLinks = array();

// Pull all page titles and links
while($row = $STH->fetch()) {
    $allLinks[] = $row;
} 

// Encode array to JSON
$je = json_encode($allLinks);

// Write to file
$fp = fopen('links.json', 'w');
fwrite($fp, $je);
fclose($fp);
4

1 回答 1

2

我希望这段代码对你有用

<script type="text/javascript" src="jquery-1.7.2.min.js"></script>

<script type="text/javascript">
       $.getJSON('links.json', function(json) {
          // alert("JSON Data: " + json[1].pagetitle);

           $.each(json, function(i,val){
                 var li_populate = "<li>"+i+"+ val +"</li>"; 
                  $("#myul").append(li_populate);

            })


       });
于 2012-04-09T18:23:16.847 回答