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 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器