2012-03-04 22 views
1

我有從我的數據庫ajax​​樣式獲取數據的代碼。例如每次9個,當我想要更多顯示時,按下更多按鈕。當我離開頁面時發生問題。當我返回時,即使我使用後退按鈕,我必須再次按下更多按鈕才能到達我所在的位置。將會話應用到這段代碼

是否有應用會話記住上次計數

的Javascript同一頁上loadmore.php的方式

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/ 
libs/jquery/1.3.0/jquery.min.js"></script> 
<script type="text/javascript"> 
$(function() 
{ 
$('.more').live("click",function() 
{ 
var ID = $(this).attr("id"); 
if(ID) 
{ 
$("#more"+ID).html('<img src="moreajax.gif" />'); 

$.ajax({ 
type: "POST", 
url: "ajax_more.php", 
data: "lastmsg="+ ID, 
cache: false, 
success: function(html){ 
$("ol#updates").append(html); 
$("#more"+ID).remove(); // removing old more button 
} 
}); 
} 
else 
{ 
$(".morebox").html('The End');// no results 
} 

return false; 
}); 
}); 
</script> 

這是主要的PHP腳本loadmore.php

<div id='container'> 
<ol class="timeline" id="updates"> 

<?php 
include('config.php'); 
$sql=mysql_query("select * from messages ORDER BY msg_id DESC LIMIT 9"); 
while($row=mysql_fetch_array($sql)) 
{ 
$msg_id=$row['msg_id']; 
$message=$row['message']; 
?> 
<li> 
<?php echo $message; ?> 
</li> 
<?php } ?> 
</ol> 

//More Button here $msg_id values is a last message id value. 
<div id="more<?php echo $msg_id; ?>" class="morebox"> 
<a href="#" class="more" id="<?php echo $msg_id; ?>">more</a> 
</div> 

</div>; 

接下來是php,它叫做ajax_more.php

<?php 
include("config.php"); 
if(isSet($_POST['lastmsg'])) 
{ 
$lastmsg=$_POST['lastmsg']; 
$lastmsg=mysql_real_escape_string($lastmsg); 
$result=mysql_query("select * from messages where msg_id<'$lastmsg' order by msg_id desc limit 9"); 
while($row=mysql_fetch_array($result)) 
{ 
$msg_id=$row['msg_id']; 
$message=$row['message']; 
?> 
<li> 
<?php echo $message; ?> 
</li> 
<?php 
} 
?> 

//More Button here $msg_id values is a last message id value. 
<div id="more<?php echo $msg_id; ?>" class="morebox"> 
<a href="#" id="<?php echo $msg_id; ?>" class="more">more</a> 
</div> 
<?php 
} 
?> 

如果任何人可以照亮任何光線。我會非常感謝

Steve

回答

0

JavaScript有能力讀取/寫入cookie。例如:

document.cookie = 
    'msgCount=9; expires=Sun, 4 Mar 2012 20:47:11 UTC; path=/'; 

這裏有發現,用於創建,讀取和刪除的cookie一些有用的JavaScript函數:http://www.quirksmode.org/js/cookies.html

這裏也有一些很好的參考上SO:

javascript cookie, little help please

What is the "best" way to get and set a single cookie value using JavaScript

+0

不好意思看看謝謝;) – 2012-03-04 12:39:32

+0

因爲最後一個msgcount是在另一個php頁面ajax_more.php我該如何回調loadmore.php – 2012-03-04 12:49:21

0

我最近實現了這樣的設置:w爲避免這個問題,我做了一個帽子,把會話設置代碼放到AJAX腳本中,然後在主/調用腳本中,每當你回到那個頁面時,使用這些數據來適當地生成內容。如果您需要在JavaScript腳本中執行此操作,請將其作爲PHP腳本並將內容類型更改爲text/javascript(或任何MIME類型應該是的),然後您可以使用PHP動態設置JavaScript源代碼,就像使用HTML一樣......雖然這種方法工作得很好,但最終我選擇了一個純粹動態的JS解決方案 - 沒有會話變量 - 因爲我的設置從未要求您從同一頁面導航。