簡體   English   中英

從asp.net中的代碼調用jquery函數似乎不起作用

[英]Calling a jquery function from code behind in asp.net doesn't seem to work

我在將記錄插入數據庫后調用了一個jquery函數...

ScriptManager.RegisterClientScriptBlock(LbOk, typeof(LinkButton), "json",
                             "topBar('Successfully Inserted');", true);

我已將其包含在我的母版頁中,用於在回發后執行jquery函數,

<script type="text/javascript">
    function load() {
 Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
      }
    function EndRequestHandler()
       {
           topBar(message);
     }


 function topBar(message) {
    alert(a);
    var alert = $('<div id="alert">' + message + '</div>');
    $(document.body).append(alert);
    var $alert = $('#alert');
    if ($alert.length) {
        var alerttimer = window.setTimeout(function() {
            $alert.trigger('click');
        }, 5000);
        $alert.animate({ height: $alert.css('line-height') || '50px' }, 200).click(function() {
            window.clearTimeout(alerttimer);
            $alert.animate({ height: '0' }, 200);
        });
    }
}
    </script>

<body onload="load();">

但它似乎不起作用......任何建議..

這是一個完整的工作示例:

<%@ Page Title="Home Page" Language="C#" AutoEventWireup="true" %>
<script type="text/C#" runat="server">
    protected void BtnUpdate_Click(object sender, EventArgs e)
    {
        // when the button is clicked invoke the topBar function
        // Notice the HtmlEncode to make sure you are properly escaping strings
        ScriptManager.RegisterStartupScript(
            this, 
            GetType(), 
            "key", 
            string.Format(
                "topBar({0});", 
                Server.HtmlEncode("Successfully Inserted")
            ), 
            true
        );
    }    
</script>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
    <title></title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
    <script type="text/javascript">
        function topBar(message) {
            var alert = $('<div id="alert">' + message + '</div>');
            $(document.body).append(alert);
            var $alert = $('#alert');
            if ($alert.length) {
                var alerttimer = window.setTimeout(function () {
                    $alert.trigger('click');
                }, 5000);
                $alert.animate({ height: $alert.css('line-height') || '50px' }, 200).click(function () {
                    window.clearTimeout(alerttimer);
                    $alert.animate({ height: '0' }, 200);
                });
            }
        }
    </script>
</head>
<body>
    <form id="Form1" runat="server">

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

    <asp:UpdatePanel ID="up" runat="server">
        <ContentTemplate>
            <!-- 
                 You could have some other server side controls 
                 that get updated here 
            -->
        </ContentTemplate>
        <Triggers>
            <asp:AsyncPostBackTrigger 
                ControlID="BtnUpdate" 
                EventName="Click" 
            />
        </Triggers>
    </asp:UpdatePanel>

    <asp:LinkButton 
        ID="BtnUpdate" 
        runat="server" 
        Text="Update" 
        OnClick="BtnUpdate_Click" 
    />

    </form>
</body>
</html>

假設您的代碼隱藏在UpdatePanel刷新期間運行,您的EndRequest處理程序和代碼隱藏注冊之間是否存在錯誤的交互? 應該調用topBar()兩次,一次使用“Successfully Inserted”消息,然后使用EndRequest中的未定義參數調用一次(除非消息變量定義在某處,我們在這里看不到)。

另請注意, $('#alert')可以返回多個項目。 如果多次調用topBar(),那可能就是這種情況。

對於初學者來說,做一些這樣的事情,以減輕這種意想不到的副作用:

function topBar(message) {
  var $alert = $('<div/>');

  $alert.text(message);

  $alert.click(function () {
    $(this).slideUp(200);
  });

  $(body).append($alert);

  // Doesn't hurt anything to re-slideUp it if it's already
  //  hidden, and that keeps this simple.
  setTimeout(function () { $alert.slideUp(200) }, 5000);
}

這並沒有解決EndRequest和Register * Script都執行topBar()的問題,但這應該使它們不會發生沖突,這樣你就可以更好地看到發生了什么。

嘗試一下,讓我們知道是否會改變一切。

使用Chrome和Firefox,我遇到的唯一問題是var alertalert()調用的名稱相同。

    function topBar(message) {
        alert(message);
        var alertDiv = $('<div id="alert">' + message + '</div>');
        $(document.body).append(alertDiv);
        var $alert = $('#alert');

在腳本運行時,你的body標簽可能沒有被加載,這意味着$(document.body)引用將是空的 - 哪個jquery將無聲地添加警報div。 無論哪種方式,在$(document).ready事件中包裝你的調用永遠不會傷害:

    ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "json",
                         "$(document).ready(function() { topBar('Successfully Inserted');});", true);

這不直接回答你的問題,但更多的意思是傳遞另一種技術來調用頁面方法而不使用更新面板,而是直接從jQuery。

只需裝飾你的頁面方法(在代碼隱藏的部分類中)就像這樣(它必須是靜態的):

[WebMethod]
[ScriptMethod(ResponseFormat=ResponseFormat.Json, XmlSerializeString=true)]
public static bool UpdateDatabase(string param1 , string param2)
{
    // perform the database logic here...

    return true;
}

然后,您可以直接從jQuery的$ .ajax方法調用此頁面方法:

$("#somebutton").click(function() {

  $.ajax({
    type: "POST",
    url: "PageName.aspx/UpdateDatabase",
    data: "{ param1: 'somevalue', param2: 'somevalue' }",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(data) {
      if (data.d) {
        topBar("success!");
      } else {
        topBar("fail");
      }
    }
  });

});

嘗試注冊腳本非常簡單,而且更加清晰。 無需創建Web服務。

這是一篇很棒的文章:

http://encosia.com/2008/05/29/using-jquery-to-directly-call-aspnet-ajax-page-methods/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM