c# - 为这个聊天应用程序使用 Ajax(可能与 Web 服务一起使用)

标签 c# asp.net ajax asp.net-ajax chat

我想在我的聊天应用程序中使用 Ajax,而不是每秒为新消息刷新一个 Iframe。有人告诉我使用带有 ajax 的 web 服务。我应该如何处理我的代码才能使用 Ajax?

这是显示每秒调用一次的 Iframe 的代码,Iframe src 有一个显示聊天消息的 aspx 页面

<script type="text/javascript">
            function refreshConversatio() {
             document.getElementById('iframeDisplayMessage').src = 'frmMessageDisplay.aspx';

            }
     </script>
    <body>
    <div id="divMessageDisplayPage" style="height: 724px; ">
          <asp:PlaceHolder ID="ContentPlaceHolderDisplayMessage" runat="server">
          <iframe id="iframeDisplayMessage" name="iframeDisplayMessage" width="76%" style="background-color:White;" height="95%" frameborder="0" src="frmMessageDisplay.aspx" 
    onload="document.getElementById('iframeDisplayMessage').contentWindow.scrollTo(0,document.getElementById('iframeDisplayMessage').contentWindow.document.body.scrollHeight)">
          </iframe>
          </asp:PlaceHolder> 
      </div>


    <script type="text/javascript">
            setInterval(function () { refreshConversatio(); }, 1000)


        </script>
 </body> 

这是在 Iframe 中调用的 Aspx 页面,它具有显示消息的文字

<div id="divConversation"  style="width: 100%;">
        <asp:Literal ID="RecepientConversation"  runat="server"/>
</div>

这是尚未使用过的 Ajax 代码,我不知道在上面的应用程序中在哪里以及如何使用它

<!DOCTYPE HTML>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <!-- Reference to google J-Query api.
    You can download and add jquery javasripts files to you soln.-->
    <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
    <title></title>
</head>
<body>

    <script type="text/javascript">
        function callService() {
            //url of your web service
            $.ajax('May be url of web service to be written here',
        {
            beforeSend: function (xhr) { },
            complete: function () { },
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            jsonp: 'callback',
            type: 'POST',
            error: function (xhr, ajaxOptions, thrownError) {

                //Function will be called when any error occcured.
                alet(thrownError);
            },
            success: function (data) {
                if (!data.d) {

                    //Cound not find data.
                }
                else {
                    if (curdata != data.d) {
                        //result of you web method is stored in data.d object. 

                        //TODO : Work with you data here.
                        alert(data.d);
                    }
                }
            }
        });
        }
        callService();

    </script>
</body>
</html>

回发后

 if (!Page.IsPostBack)
{
}
    if(dt.Rows.Count != 0)
   {


      showOnPage.Append("<div style='background-color:ALICEBLUE;float:left; width:100%; word-wrap: break-word;font-size:14px;'><pre><font color='green'><b><div style='background-color:ALICEBLUE; margin-right:410px;'>" + dt.Rows[i][2].ToString() + " Says: </b></font></pre></div><div style='background-color:ALICEBLUE;font-size:14px;float: left;width: 410px;margin-left: -410px; word-wrap: break-word;font-size:14px;'><pre><font>" + dt.Rows[i][0].ToString() + "</font></pre></div><div style='background-color:ALICEBLUE; word-wrap: break-word;'><p style='color:#8B8A8A; margin-top:0'>Sent at " + Convert.ToDateTime(dt.Rows[i][1]).ToLongTimeString() + "</p></div><div style='clear:both;'></div>");
}       


RecepientConversation.Text=showOnPage.ToString();

最佳答案

好的,那么您可以轻松地使用 Asp.net 提供的基于 Ajax 的更新面板。

javascript 代码:重复触发更新,把它放在 head 部分

<script type="text/javascript" language="javascript">

function worker() {
    __doPostBack('<%=updateComments.ClientID %>', null);
    setTimeout(worker, 5000); // 5000= 5 seconds i.e section will get refereshed in intervals of 5 second
}

</script>

标记:在更新面板中包含要异步更新的部分。您还必须将脚本管理器放置在您的代码中,如下所示。

<asp:ScriptManager ID="manager" runat="server" ></asp:ScriptManager> 

<asp:UpdatePanel ID="updateComments" runat="server">
     <ContentTemplate>
          <div id="divConversation"  style="width: 100%;">
              <div style='background-color: ALICEBLUE; float: left; width: 100%; word-wrap: break-word;
    font-size: 14px;'>
    <pre><font color='green'><b>
        <div style='background-color: ALICEBLUE; margin-right: 410px;'>
        <asp:Literal ID="ltrlFirst" runat="server"></asp:Literal>
         Says: </b></font></pre>
</div>
<div style='background-color: ALICEBLUE; font-size: 14px; float: left; width: 410px;
    margin-left: -410px; word-wrap: break-word; font-size: 14px;'>
    <pre><font>
    <asp:Literal ID="ltrlSecond" runat="server"></asp:Literal>
    </font></pre>
</div>
<div style='background-color: ALICEBLUE; word-wrap: break-word;'>
    <p style='color: #8B8A8A; margin-top: 0'>
        Sent at 
        <asp:Literal ID="ltrlThird" runat="server"></asp:Literal>
        </p>
</div>
          </div>
     </ContentTemplate>
</asp:UpdatePanel>

还要确保字面量是在此之外的数据边界,即它应该是在每个回发上都有边界的数据,而不仅仅是首先。

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    { 

     }

     BindCommentData(); // New method which binds data.

}


Private void BindCommentData()
{
    // Here you get the dt..

    if(dt.Rows.Count != 0)
    {
      ltrlFirst.Text = dt.Rows[i][2].ToString();
      ltrlSecond.Text = dt.Rows[i][0].ToString();
      ltrlThird.Text = Convert.ToDateTime(dt.Rows[i][1]).ToLongTimeString();
    }
}

关于c# - 为这个聊天应用程序使用 Ajax(可能与 Web 服务一起使用),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19945682/

相关文章:

asp.net - 将web应用项目ascx编译成dll

c# - 如何使用 MySqlDataReader 返回多个表?

c# - 在 Visual Studio 中使用 Windows 身份验证服务进行客户端开发

javascript - 当新数据插入 mysql 时,ajax 通知警报弹出或发出声音

javascript - RegisterStartupScript 不再在 asp.net 中工作

c# - 如何在 Linq 或 SQL 中递归调用 Where 子句

c# - 当列表可以附加其他任务时等待 Task.WhenAny(List<T>) 的适当模式

c# - 为什么 C# 不支持 base.base?

c# - 有没有一种类型化的方法来在 C# 中声明方法名称

javascript - 使用Ajax方法检索数据时显示加载