使用者點擊提交按鈕後通過Ajax提交參數給伺服器,伺服器添加進資料庫後返回添加結果,頁面根據伺服器返回的結果判斷,如果添加成功了,就把內容更新到頁面上(append()方法).
對於使用者來說,整個過程是無重新整理的,不會打斷使用者操作.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="無重新整理評論.aspx.cs" Inherits="Ajax_無重新整理評論" %><!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> <script src="../js/jquery-1.4.2.js" type="text/javascript"></script> <script type="text/javascript"> function InsertComment() { var name = $("#TextBox2").val(); var content= $("#TextBox3").val() ; var time=new Date(); $.post("InsertComment.ashx", { "name": name, "content": content, "time": time }, function(data, status) { if (status == "success") {//伺服器返回成功 if (data == "success") {//添加成功 var tr = $("<tr><td>暱稱:" + name + "<br/>時間:" + time + "</td><td>內容:" + content + "</td></tr>"); $("#table1").append(tr);//把內容更新到頁面 } else if (data == "error") { alert("添加失敗"); } else { alert("ajax error"); } } else { alert("ajax error"); } }); } </script></head><body> <form id="form1" runat="server"> <div> <asp:TextBox ID="TextBox1" runat="server" Height="346px" Width="656px"></asp:TextBox> </div> <p> 評論區:</p> <asp:Repeater ID="Repeater1" runat="server" DataSourceID="AccessDataSource1"> <HeaderTemplate><table id="table1"></HeaderTemplate> <ItemTemplate><tr><td>暱稱:<%# Eval("name") %><br />時間:<%# Eval("uptime") %></td><td>內容:<%# Eval("content") %></td></tr></ItemTemplate> <FooterTemplate></table></FooterTemplate> </asp:Repeater> <asp:AccessDataSource ID="AccessDataSource1" runat="server" DataFile="~/App_Data/77feel.mdb" SelectCommand="SELECT [name], [content], [uptime] FROM [comment] ORDER BY [uptime]"> </asp:AccessDataSource> <br /> 發表評論:<br /> 暱稱:<input ID="TextBox2" type="text" Width="157px"/> <br /> 內容:<input ID="TextBox3" type="text" Height="73px" Width="234px"/> <br /> <input ID="Button1" type="button" value="提交" onclick="return InsertComment()" /> </form> </body></html>
伺服器代碼:InsertComment.ashx
<%@ WebHandler Language="C#" Class="InsertComment" %>using System;using System.Web;public class InsertComment : IHttpHandler { public void ProcessRequest (HttpContext context) { context.Response.ContentType = "text/plain"; var response = context.Response; var request = context.Request; string name = request["name"]; string content = request["content"]; string time = request["time"]; jiang_Db newdb = new jiang_Db(); try { newdb.ExecSql_None(string.Format("insert into comment([name],[content],[uptime]) values('{0}','{1}','{2}')",name,content,time)); response.Write("success"); } catch (Exception) { response.Write("error"); } } public bool IsReusable { get { return false; } }}