AJAX autorefresh making only last entry visible !
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 :
- User A opens the forum
- He gets questions qlatest,q1,q2,q3 . Where div containg qlatest refreshes every 1 sec
- User B posts a question qlatest2
- 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:
- Add some data source that returns last asked question.
- 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:
- Long polling
- JSON format
- jQuery.requestJSON() jQuery function
- Maybe some effects to make the question change smoother (like slide out and slide in)
精彩评论