我的JSON数组有问题。在第一次加载时,顺序不是应该的(在SQL查询中定义)。
所以主要的问题是,在页面加载时,即当使用lastPoll = null调用SQL查询时 - 结果不按time1 DESC排序,但它们按照s.id ASC排序。当我输入一个新结果,然后在查询中设置lastPoll时运行查询,然后将最新的内容添加到顶部,就像它应该的那样。
奇怪的是 - 如果我在push.php中使用URL中的正确params查看原始JSON响应,则响应是正确的并且顺序正确。那么,问题必须在于解析?
这是SQL查询:
$getActivityUpdates1 = mysql_query("
SELECT
s.id, u.name, u.profilePic, s.userid, s.content, s.time1, s.imageKey
FROM
status_updates s
INNER JOIN
users1 u ON u.id = s.userid
WHERE
competitionId = '$competitionId' AND s.time1 > '$lastPoll'
ORDER BY s.time1 DESC");
$results = array('items' => array());
while ($row = mysql_fetch_array($getActivityUpdates1))
{
$results['items'][] = array(
'statusid' => $row['id'],
'name' => $row['name'],
'profilePic' => $row['profilePic'],
'content' => $row['content'],
'time1' => $row['time1'],
'imageKey' => $row['imageKey'],
);
}
die(json_encode($results));
?>
这是我重新运行查询的Javascript。
var lastPoll = null;
function loadActivity(onDone) {
var competitionId = $("body").attr("data-competitionId");
console.log(lastPoll);
if (lastPoll == null) { // We have never polled, we want to pull everything and populate the list.
url = "push.php?competitionId=" + competitionId + "&lastPoll=1999-01-01 22:00:00";
} else { // We have polled once, send the date and time of that last poll to capture only new entries.
url = "push.php?competitionId=" + competitionId + "&lastPoll=" + lastPoll;
}
$.get(url, function(data) {
jsonData = $.parseJSON(data);
var spot = $("#activityspot");
var template = spot.find(".template");
for (var j = 0; j < jsonData.items.length; j++) {
var entryData = jsonData.items[j];
var entry = template.clone();
entry.removeClass("template");
entry.find(".message").text(entryData.statusid);
spot.prepend(entry);
}
if (onDone) {
onDone();
}
lastPoll = js_yyyy_mm_dd_hh_mm_ss();
});
}
答案 0 :(得分:0)
您以反向时间顺序生成结果,但随后也以相反的顺序将其添加到页面中(使用.prepend
)。最终结果是两次逆转相互抵消,使得每批结果以升序时间顺序添加到列表顶部。
如果意图是以相反的顺序实际显示它们,只需从查询中删除DESC
限定符并依赖.prepend
调用将每个连续的条目添加到页面顶部