繁体   English   中英

Javascript 倒计时调用 asp.net 代码隐藏代码

[英]Javascript countdown call asp.net codebehind code

运行 default.aspx 时,我需要调用 function Search(int count) 后面的 asp.net 代码。 第一次调用 function 时,int 计数应为 5。如果 function 返回 True,则 function 不应再次运行。

If the function returns false, run the function again with count = 4. If it still returns false, run the function again with count = 3. Do this until count = 0. It should be 1 second between each time the funtions runs.

jacascript 在 default.aspx 中是否有聪明的方法来解决这个问题?


默认.aspx

Javascript here...

<asp:Literal runat="server" id="litStatus" />

默认.aspx.cs

protected bool Search(int count)
{
    bool status = false;

    if (count > 0)
    {
        if (Something....)
        {
            litStatus.Text = "Found";
            status = true;
        }
        else
        {
            litStatus.Text = string.Format("Please wait ({0})...", count);
        }
    }
    else
    {
        litStatus.Text = "Not found";
    }
    return status;
}

首先将搜索function改为WebMethod

   [WebMethod]
    public static object Search(int count)
    {
        bool status = false;

        if (count > 0)
        {
            if (count % 2 == 0)
            {
                return new { Result = true, StatusText = "Found" };
            }
            else
            {
                return new { Result = false, StatusText = string.Format("Please wait ({0})...", count) }; 
            }
        }
        else
        {
            return new { Result = false, StatusText = "Not found" };

        } 
    }

更改文字 ID 模式:

 <asp:Literal runat="server" ClientIDMode="Static" id="litStatus" />

然后使用 Jquery 调用 webmethod

   <script>  
        let count = 5;
     var   callSearch = function () {
            var Data = JSON.stringify({ count: count });

            $.ajax({

                url: "/Default.aspx/Search",
                data: Data,
                type: "POST",
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                success: function (response) {
$('#litStatus'').text(response.d.StatusText );
                    if (!response.d.Result) {
                        --count;
                        if (!count==0) { 
                            setTimeout(callSearch, 1000);
                        }
                    } else {
                        alert(response.d);
                    }
                }
            });
        }
        callSearch()

    </script>

你完成了..希望我的回答对你有帮助

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM