您的位置:首页 > 其它

利用Ajax实现无刷新回贴demo

2011-08-13 12:43 211 查看
后端是用.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实现但感觉没有必要花那么大代价。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: