开发者

AJAX autorefresh making only last entry visible !

开发者 https://www.devze.com 2023-03-03 14:21 出处:网络
Iam new to PHP . I wanted to make a forum where users can ask ques开发者_StackOverflow中文版tions.I am using ajax to auto refresh the page.But it creates some problems...

Iam new to PHP . I wanted to make a forum where users can ask ques开发者_StackOverflow中文版tions.I am using ajax to auto refresh the page.But it creates some problems...

Firstly, if I make that particular div ,where most recent question will be displayed,refresh only the latest question is displayed . let me clear it with an ex :

  1. User A opens the forum
  2. He gets questions qlatest,q1,q2,q3 . Where div containg qlatest refreshes every 1 sec
  3. User B posts a question qlatest2
  4. qlatest is replaced by qlatest2 !

Now should I make whole div conatining all the questions make refresh?


If I understand correctly you want to create something like the Twitter feed where the latest item is displayed on top of each other.

The reason that the entire DIV refreshes is because you are rewriting the entire inner HTML of that DIV. To avoid this, use .appendChild() and program your PHP callback file to only pull the latest record from the database.

http://www.ezineasp.net/post/Javascript-Append-Div-Contents.aspx

JQuery also has some very useful functions adding children. I suggest using a Javascript library if you are new to AJAX calls.


You have to:

  1. Add some data source that returns last asked question.
  2. Invoke that data source on a constant interval and load returned question into the div..

The simplest to explain is the following solution: Write JavaScript code that uses JS builtin function setInterval() to load eg. script last_question.php into the div. You can do it eg. using jQuery load() function, which can look eg. like this (assuming your div has ID of "last_question"):

jQuery('#last_question').load('last_question.php');

Of course it can be optimized. To do so, read about:

  1. Long polling
  2. JSON format
  3. jQuery.requestJSON() jQuery function
  4. Maybe some effects to make the question change smoother (like slide out and slide in)
0

精彩评论

暂无评论...
验证码 换一张
取 消