我的 JSON 数组有问题。在第一次加载时,顺序不是应有的(在 SQL 查询中定义)。
所以主要问题是,在页面加载时,即使用 lastPoll=null 调用 SQL 查询时 - 结果不是按 time1 DESC 排序的,而是按 s.id ASC 排序的。当我输入一个新结果,然后使用查询中设置的 lastPoll 运行查询时,最新的将被添加到顶部,这是应该的。
奇怪的部分是 - 如果我在 URL 中使用正确的参数查看 push.php 中的原始 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();
});
}