我對JSON和jQuery很陌生。在這裏,我想要做的是從JSON中獲取數據並將其顯示在html表格中。問題是當我將document.write(ht);
寫入head
部分的html文件時,一切正常。但是當我將document.write(ht);
寫入html這樣的主體時,它只顯示undefined
作爲輸出。我無法弄清楚爲什麼會這樣。變量無法從外部提取
以下是text.json文件:
{
"red":"new_small.gif",
"green":"new_small.gif"
}
以下是HTML文件:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script src="jquery-1.7.2.js"></script>
<script type="text/javascript">
var items = [];
var ht;
$.getJSON('text.json', function(data) {
ht='<table>';
$.each(data, function(key, val) {
ht+= '<tr><td>' + key + '</td><td><img src="' + val+ '"></td></tr>';
});
ht+='</table>';
}).success(function() { alert("success"); })
.error(function() { alert("error"); })
.complete(function() { alert("complete"); });
</script>
</head>
<body>
<script>
document.write(ht);
</script>
</body>
</html>
http://jsfiddle.net/uXWMu/ – Dion 2012-04-11 09:01:29