利用 javascript 達到非同步效果

摘要:利用 javascript 達到非同步效果

########################     aspx              ######################################

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <script type="text/javascript" language="javascript">
        function ReceiveServerData(args, context) {
            document.getElementById("price1").innerText = args;
        }
    </script>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        目前股價:<asp:Label ID="price1" runat="server"></asp:Label>
        <asp:Button ID="Button1"
            runat="server" Text="Button"
            onclientclick="CallServer('','');return false;" />
    </div>
    </form>
</body>
</html>

############################  cs ###########################################

public partial class 非同步1 : System.Web.UI.Page, ICallbackEventHandler
{
    public string str;
    //註冊非同步使用的javascript
    protected void Page_Load(object sender, EventArgs e)
    {
        ClientScriptManager csm = Page.ClientScript;
        string s = csm.GetCallbackEventReference(this, "args", "ReceiveServerData", "context");
        string strcallback = "function CallServer(args,context){" + s + ";};";
        csm.RegisterClientScriptBlock(this.GetType(), "CallServer", strcallback, true);

        //註冊語法如下:
        //function CallServer(args,context)
        //{ WebForm_DoCallback('__Page',args,ReceiveServerData,context,null,false); };

    }
   
    //非同步傳回結果值
    public string GetCallbackResult()
    {
        return str;
    }

    //非同步運算
    public void RaiseCallbackEvent(string eventArgument)
    {
        str = (5000).ToString("C");
    }
}