【问题标题】:JSON response is not ordering properly according to SQL queryJSON 响应未根据 SQL 查询正确排序
【发布时间】:2013-09-22 09:01:03
【问题描述】:

我的 JSON 数组有问题。首次加载时,顺序不是应有的(在 SQL 查询中定义)。

所以主要问题是,在页面加载时,即当使用 lastPoll=null 调用 SQL 查询时 - 结果不是按 time1 DESC 排序的,而是按 s.id ASC 排序的。当我输入一个新结果,然后使用查询中设置的 lastPoll 运行查询时,最新的将被添加到顶部,这是应该的。

奇怪的部分是 - 如果我在 push.php 中查看原始 JSON 响应并在 URL 中使用正确的参数,则响应是正确的并且顺序正确。那么,问题一定出在解析上?

这是 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();

    });
}

【问题讨论】:

    标签: javascript php mysql json


    【解决方案1】:

    您正在以相反的时间顺序生成结果,但随后也以相反的顺序将它们添加到页面(使用.prepend)。最终结果是两个反转相互抵消,使得每批结果按升序时间顺序添加到列表顶部。

    如果您的意图实际上是让它们以相反的顺序显示,只需从查询中删除 DESC 限定符并依靠 .prepend 调用将每个连续条目添加到页面顶部。

    【讨论】:

    • 我能再问一个问题吗?关于为每个活动构建模板 - 我可以将更多内容从 JSON 添加到这两行吗?例如,如果我还想将图像放在那里,并给该图像一个特定的类,我如何将所有这些放入一个“条目”? entry.find(".message").text(entryData.statusid); spot.prepend(entry);
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-14
    • 1970-01-01
    • 1970-01-01
    • 2018-04-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多