這篇文章主要介紹了jQuery結合AJAX之在頁面滾動時從服務器加載數據,文中示例服務器端為C#程序,需要的朋友可以參考下
簡介
文本將演示怎么在滾動滾動條時從服務器端下載數據。用AJAX技術從服務器端加載數據有助于改善任何web應用的性能表現,因為在打開頁面時,只有一屏的數據從服務器端加載了,需要更多的數據時,可以隨著用戶滾動滾動條再從服務器端加載。
背景
是Facebook促使我寫出了在滾動條滾動時再從服務器加載數據的代碼。瀏覽facebook時,我很驚訝的發現當我滾動頁面時,新的來自服務器的數據開始插入到此現存的數據中。然后,對于用c#實現同樣的功能,我在互聯網上了查找了相關信息,但沒有發現任何關于用c#實現這一功能的文章或者博客。當然,有一些Java和PHP實現的文章。我仔細的閱讀了這些文章后,開始用c#寫代碼。由于我的C#版本運行的很成功,所以我想我愿意分享它,因此我發表了這邊文章。
代碼
只需要很少的幾行代碼我們就能在滾動時完成加載。滾動頁面時,一個WebMethod將被客戶端調用,返回要插入客戶端的內容,同時,在客戶端,將把scroll事件綁定到一個客戶端函數(document.ready),這個函數實現從服務器端加載數據。下面詳細說說這兩個服務器端和客戶端方法。
服務器端方法:這個方法用來從數據庫或者其他數據源獲取數據,并根據數據要插入的控件的格式來生成HTML串。這里我只是加入了一個帶有序列號的消息。
[WebMethod]
代碼如下:
public static string GetDataFromServer()
{
string resp = string.Empty;
for(int i = 0; i <= 10; i++)
{
resp += "
" + counter++ +
" This content is dynamically appended " +
"to the existing content on scrolling.
" ;
}
return resp;
}
若你要從數據庫加載數據,可以如下修改代碼:
[WebMethod]
代碼如下:
public static string GetDataFromServer()
{
DataSet ds = new DataSet();
// Set value of connection string here
string strConnectionString = ""; // Insert your connection string value here
SqlConnection con = new SqlConnection(strConnectionString);
// Write the select command value as first parameter
SqlCommand command = new SqlCommand("SELECT * FROM Person", con);
SqlDataAdapter adp = new SqlDataAdapter(command);
int retVal = adp.Fill(ds);
string resp = string.Empty;
for (int i = 1; i <= ds.Tables[0].Rows.Count; i++)
{
string strComment = string.Empty;
if (ds.Tables != null)
{
if (ds.Tables[0] != null)
{
if (ds.Tables[0].Rows.Count > 0)
{
if (ds.Tables[0].Rows.Count >= i - 1)
{
if (ds.Tables[0].Rows[i - 1][0] != DBNull.Value)
{
strComment = ds.Tables[0].Rows[i - 1][0].ToString();
}
}
}
}
}
resp += "
" +
新聞熱點
疑難解答