douhang8991 2015-02-25 17:07
浏览 228
已采纳

如何通过`echo json_encode($ data);`获取所有数据

I want to update user wall by my below script if new data added in sql within last 15 second.

It's update fine if I just use only one data $data = $row['description']; in server.php file.

When I am going to array all data in server.php file to display full post and make my script as below, It's display [object Object] continuously.

So I want to display newly added full post with user img, name, detail etc.

But I have no idea about how to do it.

Please give me a guideline.

server.php

include("../db.php");
global $dbh;
header('Content-Type: application/json; charset=utf-8');
while (true) {
date_default_timezone_set('Asia/Dhaka');
//fetch data 
$datetime = date('Y-m-d H:i:s', strtotime('-15 second'));
$results = mysqli_query($dbh,"SELECT * FROM comments WHERE qazi_id='1012' AND date >= '$datetime' ORDER BY date DESC LIMIT 1") or die(mysqli_error($dbh));
$rows =  mysqli_fetch_assoc($results);

$data = array();

$data['id'] = $rows['id'];
$data['qazi_id'] = $rows['qazi_id'];
$data['likes'] = $rows['likes'];
$data['username'] = $rows['username'];
$data['img'] = $rows['img'];
$data['description'] = $rows['description'];
$data['url'] = $rows['url'];
$data['parent_id'] = $rows['parent_id'];
$data['date'] = $rows['date'];

//has data
if (!empty($data)) {
    echo json_encode($data);
    flush();
    exit(0);
}
sleep(5);
}

JS Script:

function addmsg(type, msg){
    $("#messages").append(
        "<div class='msg "+ type +"'>"+ msg +"</div>"
    );
}

function waitForMsg(){
    $.ajax({
        type: "GET",
        url: "server.php",
        async: true, 
        cache: false,
        timeout:15000, 
        success: function(data){ 
            addmsg("new", data); 
            setTimeout(
                waitForMsg, 
                1000 
            );
        },
        error: function(XMLHttpRequest, textStatus, errorThrown){
            setTimeout(
                waitForMsg, 
                15000); 
        }
    });
};

$(document).ready(function(){
    waitForMsg(); 
});

Html:

<div id="messages">

</div>
  • 写回答

2条回答 默认 最新

  • donglang8008 2015-02-25 17:19
    关注

    In the "simple" example ($data = $row['description'];) your data is returned as a string, that's why it works. When you sent your object back to the page things get more difficult. You still try to print the object as a string (JavaScript translates and shows you [Object Object], saying that you actually retrieved an object). You need to supply the proper index/key to msg to retrieve the correct info.

    For example: msg['description'] should return the description.

    function addmsg(type, msg){
        $("#messages").append(
            "<div class='msg "+ type +"'>"+ msg["description"] +"</div>"
        );
    }
    

    Basically your data is returned as this

    msg = {
             "username" : "foo",
             "description" : "bar",
             etc....
          }
    

    It's returned as a JavaScript object from which you can retrieve properties normally.

    • msg.username or
    • msg["username"]

    To build your message you need to build your message object containing the various properties of msg (or data).

    function addmsg(type, msg){
        $("#messages").append(
            "<div class='msg "+ type +"'>User " + msg["username"] + "sent: " + msg["description"] +"</div>"
        );
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog