後端是用.net 中的WebServices實現的存諸到資料庫。 Ajax調用WebSerivce特別是用post提交時要注意協議及放在IIS伺服器上才能正常調用。
HTML代碼:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>無重新整理顯示回帖</title>
<style type="text/css">
body
{
font-size: 12px;
color: #414141;
margin: 0px;
padding: 0px;
}
#divView
{
margin: 0px;
padding: 0px;
width: 30%;
}
#divView ul
{
list-style-type: none;
line-height: 28px;
margin: 0px;
padding: 0px;
}
#divView li
{
border: solid 1px #ccc;
border-bottom: 0px;
line-height:28px;
}
#ul
{
list-style-type: none;
line-height: 24px;
margin: 0px;
padding: 0px;
width:30%;
}
#ul li
{
border:solid 1px #ccc;
border-bottom:0px;
line-height:28px;
}
.input
{
border:solid 1px #ccc;
width:200px;
background-color:#fff;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div id="divView" runat="server">
</div>
<ul id="ul">
<li style="background-color:#ccc;font-size:14px;font-weight:100">回帖</li>
<li>標題:<input type="text" id="txtTitle" class="input" /></li>
<li>內容:<textarea class="input" id="ttaContext" rows="5" cols="20"></textarea></li>
<li>
<input type="button" value="提交" id="btnSubmit" /></li>
</ul>
</form>
</body>
<script type="text/javascript">
var xmlHttp;
function $(str){return document.getElementById(str);}
function createXmlHttp()
{
xmlHttp=window.ActiveXObject?new ActiveXObject("msxml2.xmlHttp"):new XMLHttpRequest();
}
function ajax()
{
var title=$("txtTitle").value;
var context=$("ttaContext").value;
if(title=="")
{
alert("請輸入標題");
$("txtTitle").focus();
}else if(context=="")
{
alert("請輸入內容");
$("ttaContext").focus();
}else
{
createXmlHttp();
xmlHttp.onreadystatechange=function()
{
if(xmlHttp.readyState==4)
{
var temp=xmlHttp.responseText;
var reg=/>(\d)</ig;
var regex=/\d/ig;
if(parseInt(regex.exec(reg.exec(temp)))>0)
{
$("txtTitle").value="";
$("ttaContext").value="";
if($("liNull")!=null)
{
$("divView").removeChild($("liNull"));
}
var ul=document.createElement("ul");
var li_t=document.createElement("li");
var li_c=document.createElement("li");
li_t.innerHTML="<b>"+title+"</b>";
ul.appendChild(li_t);
li_c.innerHTML=context;
ul.appendChild(li_c);
$("divView").appendChild(ul);
}else
{
//調用提示層的正在發送伺服器.....
}
}
}
xmlHttp.open("post","WebService.asmx/InsertPostById",true);
xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlHttp.send("title="+escape(title)+"&context="+escape(context));
}
}
$("btnSubmit").onclick=ajax;
</script>
</html>
C#代碼:
/// <summary>
/// 添加回帖方法
/// </summary>
/// <param name="title">資訊標題</param>
/// <param name="context">資訊內容</param>
/// <returns></returns>
[WebMethod]
public string InsertPostById(string title, string context)
{
SqlCommand cmd = new SqlCommand();
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["SQL_STRING"].ToString()))
{
conn.Open();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO TBPOSTS(PTITLE,PCONTEXT) VALUES(@PTITLE,@PCONTEXT)";
SqlParameter[] parms = new SqlParameter[]
{
new SqlParameter("@PTITLE",SqlDbType.NVarChar,100),
new SqlParameter("@PCONTEXT",SqlDbType.NVarChar,3000)
};
parms[0].Value = Server.UrlDecode(title);
parms[1].Value = Server.UrlDecode(context);
cmd.Parameters.AddRange(parms);
string val = cmd.ExecuteNonQuery().ToString();
cmd.Parameters.Clear();
return val;
}
}
頁面載入C#方法:
protected void Page_Load(object sender, EventArgs e)
{
List<post> postList = GetPostList();
if (postList.Count <= 0)
{
this.divView.InnerHtml = "<li id='liNull'>暫無回貼!</li>";
return;
}
foreach (post postInfo in postList)
{
string temp = "<ul><li><b>" + postInfo.PTitle + "</b></li><li>" + postInfo.PContext + "</li></ul>";
this.divView.InnerHtml += temp;
}
}
public List<post> GetPostList()
{
SqlCommand cmd = new SqlCommand();
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["SQL_STRING"].ToString());
try
{
conn.Open();
cmd.CommandType = CommandType.Text;
cmd.Connection = conn;
cmd.CommandText = "SELECT PID,PTITLE,PCONTEXT FROM TBPOSTS";
List<post> posts = new List<post>();
using (SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
{
while (rdr.Read())
{
post postInfo = new post(rdr.GetInt32(0), rdr.GetString(1), rdr.GetString(2));
posts.Add(postInfo);
}
return posts;
}
}
catch
{
conn.Close();
return null;
}
}
//這裡聲明了一個類中類
public class post
{
public post() { }
/// <summary>
///
/// </summary>
/// <param name="pid">ID</param>
/// <param name="ptitle">標題</param>
/// <param name="pcontext">內容</param>
public post(int pid, string ptitle, string pcontext)
{
this.PID = pid;
this.PTitle = ptitle;
this.PContext = pcontext;
}
public int PID;
public string PTitle;
public string PContext;
}
當然頁面載入也可以用Ajax實現但感覺沒有必要花那麼大代價。。