drfb52000 2015-06-16 12:09
浏览 59
已采纳

ajax和php之间的数组json

I'm developing a simple guestbook and I want to update the table with all messages without refreshing the page because if someone it's writing a comment and the page refreshes the comment will be lost. So I began writing some code with ajax to update the table but I don't know how to send an array (with comment, username, date ecc) from php to ajax. In the database I have a column named "wrote" and it can be 0 (unread) or 1 (read). 1 it's when the messages it's already on the table. This is what I've done since now, maybe it's wrong

getGuest.php

<?php

include("Database.php");

$Database = new Database( "localhost", "root", "1234");
$Database->connectToServer();
$Database->connectToDatabase("test");

$result = $Database->unreadMessages();

$rows=mysql_fetch_array($result);

echo json_encode($rows);
?>

Script.js

window.onload = function(){
    interval = window.setInterval('updateGuest()',5000);
}



function updateGuest() {
    $.ajax({
        url: 'getGuest.php',
        method: 'get',
        success: on_getGuest_success,
        error: on_error
    });
}

function on_getGuest_success(data) {
    for(var i=0; i<data.length;i++) {
       // HERE I WANT TO ADD A ROW WITH ALL MESSAGE UNREAD BUT I DONT KNOW WHAT I HAVE TO DO
    }

}

function on_error() {
    //do something

}
  • 写回答

1条回答 默认 最新

  • dongyongan9941 2015-06-16 13:31
    关注
    1. Make sure the JSON contains an array
    2. Add headers
    3. use getJSON

    Like this:

    PHP

    $data = array(); 
    while ($row = mysql_fetch_assoc($result)) { 
      $data[] = $row; 
    } 
    header("content-type: application/json");
    echo json_encode($data);
    

    JS:

    $(function() { // when page has loaded
      var tId = setInterval(function() { // save the tId to allow to clearTimeout if needed
        $.getJSON("getGuest.php",function(data) { // call the server using jQuery's JSON access
          $('.guestbook').empty(); // empty the container
          var rows = []; // create an array to hold the rows
          $.each(data,function(_,item) { // loop over the returned data adding rows to array
            rows.push('<tr><td class="name" width="10%">' + item.name + '</td></tr>');
         });
         $('.guestbook').html(rows.join()); // insert the array as a string
        });
      },5000); // every 5 secs
    });
    

    I would personally only return what was new since last time

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示