简体   繁体   English

如何使用jQuery调用C#方法?

[英]How can I call a C# method using jQuery?

I want a C# code behind to be run every second. 我希望每秒钟运行一次C#代码。 After googling, I wrote these codes: 谷歌搜索后,我编写了以下代码:

    <script type="text/javascript">
        var myVar = setInterval(function () { start() }, 1000);
        function start() {
                time2 = 5;
                //alert("Hello");
                $.ajax({
                    type: "POST",
                    url: "WebForm1.aspx/refresh",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function () {
                        alert("Hello");
                    },
                    failure: function () {
                        alert("Error");
                    }
                });
        }
    </script>

And the code behind is: 后面的代码是:

    [System.Web.Services.WebMethod]
    public static void refresh()
    {
         //some code
    }

But nothing happens. 但是什么也没发生。 What's wrong? 怎么了?

UPDATE: I installed Firebug and observed that it is reporting "500 Internal Server Error". 更新:我安装了Firebug,并观察到它正在报告“ 500 Internal Server Error”。 What does it mean ? 这是什么意思 ?

Everything looks good. 一切看起来都很好。 But i assume you are not calling the JavaScript function. 但是我假设您没有调用JavaScript函数。

<script type="text/javascript">
        var myVar = setInterval(function () { start() }, 1000);
        function start() {
            alert('hi');
            time2 = 5;
            //alert("Hello");
            $.ajax({
                type: "POST",
                url: "default.aspx/refresh",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function () {
                    alert("Hello");
                },
                failure: function () {
                    alert("Error");
                }
            });
        }


        myVar;   //------------------> Call the function
    </script>

just call the function by calling myVar; 只需调用myVar即可调用该函数;

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

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