2015-06-16 24 views
0

我正在開發一個簡單的留言簿,並且我想更新包含所有消息的表格而無需刷新頁面,因爲如果有人正在編寫評論並且頁面刷新評論將會丟失。 所以我開始用ajax編寫一些代碼來更新表格,但我不知道如何從php到ajax發送一個數組(帶註釋,用戶名,日期ecc)。 在數據庫中,我有一個名爲「寫」的列,它可以是0(未讀)或1(讀)。 1它是什麼時候它已經在桌面上的消息。 這是因爲現在我做了什麼,也許這是錯誤的ajax和php之間的數組json

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 

} 
+0

首先'間隔是什麼新= window.setInterval ('updateGuest()',5000);'應該是'var interval = window.setInterval(updateGuest,5000);' – mplungjan

+0

重複http://stackoverflow.com/questions/11201685/mysql-fetch-array-echo-to-json? – mplungjan

+0

@mplungjan問題是我使用編碼來創建json,但我不知道如何在ajax上使用它 – untruste

回答

1
  1. 確保JSON包含數組
  2. 添加標題
  3. 使用getJSON

像這樣:

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 
}); 

我個人只返回自從上次

+0

這一個完美的作品!你能解釋我對js的每一行嗎?設置的時間間隔是每5秒收穫一次,然後呢? – untruste

+0

查看更新的腳本 – mplungjan

+0

檢查聊天請:)順便說一句我會檢查你的答案作爲'解決方案' – untruste