在這里,我利用三個頁面簡單的實現(xiàn)一個效果:
Default.aspx、1.html、GetDate.aspx
在Default.aspx綁定新聞的標題,這里,我們也可以利用ajax從數(shù)據(jù)庫中讀取數(shù)據(jù),這里就省了。
五個新聞標題,單擊傳一個Id到1.html這個頁面中。,我們的1.html還是利用昨天的那個網(wǎng)頁模板
在1.html這個頁面的HTML代碼中,我們利用js與ajax聯(lián)合來實現(xiàn)
<script language="javascript" type="text/javascript">
//首先獲取URL路徑,然后獲取傳過來的編號
var url=location.href;
var id=url.split('=');
var NewsId=id[1];
var NId=parseInt(NewsId);
if(isNaN(NId))
{
location.href="../information.html";
}
//利用ajax
var xmlhttp;
function GetStudent()
{
if(window.ActiveXObject)
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
else if(window.XMLHttpRequest)
{
xmlhttp =new XMLHttpRequest();
}
var url1="../GetDate.aspx?nid="+NId;
xmlhttp.open("GET",url1,true);
xmlhttp.onreadystatechange=ShowResult;
xmlhttp.send(null);
return false;//這里返回false就是為了屏蔽掉服務(wù)器端的時間
}
function ShowResult()
{
if(xmlhttp.readystate==4)
{
if(xmlhttp.status==200)
{
var reslut= new String( xmlhttp.responseText);
var myarr= reslut.split('|');
document.getElementById("title").innerHTML=myarr[0];
document.getElementById("content").innerHTML=myarr[1];
}
}
}
</script>
我們來看一下GetDate.aspx這個讀取數(shù)據(jù)頁的代碼
public override void ProcessRequest(HttpContext context) //這是一個內(nèi)置的方法,它是專門處理http信息的一個方法,具體講解參看:http://technet.microsoft.com/zh-cn/cc680109.aspx
{
string title = null;
string content = null;
SqlConnection conn = new SqlConnection("server=.;uid=sa;pwd=;database=mydemo");
string str = "select * from Newsinfo where NewsId=@Id";
SqlCommand com = new SqlCommand(str, conn);
com.Parameters.Add("@Id", SqlDbType.Int, 4);
com.Parameters["@Id"].Value =context.Request.QueryString["nid"];
conn.Open();
SqlDataReader dr = com.ExecuteReader();
if (dr.Read())
{
title = dr["NewsTitle"].ToString();
content = dr["NewsBody"].ToString();
}
string Str1 =title+ "|" + content;
context.Response.Write(Str1);
}
到目前為止,我們?nèi)魏螐臄?shù)據(jù)庫讀取到的數(shù)據(jù),都會在一個靜態(tài)頁面上顯示,實現(xiàn)了我們想要的結(jié)果。