我正在尝试提取数据以不断刷新来自某个来源的新闻
data.php
$fecha = $_GET['fecha'];
$feed = array();
$result = mysql_query("SELECT * FROM envivo WHERE fecha >= '".$fecha."' ORDER BY fecha DESC");
$existe = mysql_num_rows($result);
if ($existe != 0) {
while ($data = mysql_fetch_array($result)) {
$jsondata = array();
$jsondata['titulo'] = $data['titulo'];
$jsondata['link'] = $data['link'];
$jsondata['fuente'] = $data['fuente'];
$feed[] = $jsondata;
}
echo json_encode($feed);
}
live.php
<!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 profile="http://gmpg.org/xfn/11">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Live</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript">
function restults(data) {
$(data).each(function() {
$("#envivo").append("<li>Titulo: " + data.titulo + " Link: " + data.link + " Fuente: " + data.fuente + "</li>");
});
}
$(document).ready(function(){
var fecha = Math.round((new Date()).getTime() / 1000);
setInterval(function() {
$.ajax({
data: "fecha="+fecha,
type: "GET",
dataType: "json",
url: "data.php",
success: function(data){
restults(data);
}
});
}, 5000);
});
</script>
</head>
<body>
<div id="envivo">
</div>
</body>
</html>
运行index.php时,data.php通过ajax调用,返回类似这样的内容
[{ “TITULO”:“测试 1302662957" , “链接”: “HTTP:\ / \ / www.google.com”, “丰”: “朱克”},{ “TITULO”:“测试 1302662957" , “链接”: “HTTP:\ / \ / www.google.com”, “丰”: “朱克”},{ “TITULO”:“测试 1302662631" , “链接”: “HTTP:\ / \ / www.google.com”, “丰”: “朱克”}]
此时一切都很好......现在我将尝试检索并附加该数据
在firebug控制台上
[{ “TITULO”:“测试 1302662957" , “链接”: “HTTP:\ / \ / www.google.com”, “丰”: “朱克”},{ “TITULO”:“测试 1302662957" , “链接”: “HTTP:\ / \ / www.google.com”, “丰”: “朱克”},{ “TITULO”:“测试 1302662631" , “链接”: “HTTP:\ / \ / www.google.com”, “丰”: “朱克”}]
所以很好......但是在使用时
$(data).each(function() {
$("#envivo").append("<li>Titulo: " + data.titulo + " Link: " + data.link + " Fuente: " + data.fuente + "</li>");
});
我对每个值都没有定义......任何想法?
提前致谢
答案 0 :(得分:8)
$.fn.each()
旨在迭代dom元素。您需要$.each()
,它迭代任何泛型集合,例如对象数组。将您的.each()
代码更改为以下内容:
$.each(data, function(index, data) {
$("#envivo").append("<li>Titulo: " + data.titulo + " Link: " + data.link + " Fuente: " + data.fuente + "</li>");
});