0

我有以下试图调用服务器端函数的 javascript 代码:

    function server_GetStats(nodeID) {
        var result = PageMethods.getStats(nodeID);
        return result;
    }

    setInterval(function () {
        newVal = parseInt(server_GetStats(1089)) + parseInt(server_GetStats(1090));
        rate = (newVal - val) / (pollTime / updateCounterTime);
    }, pollTime);

这是被调用的服务器端函数:

    [WebMethod]
    public static int getStats(object nodeID)
    {
        int stat= 0;
        SqlConnection conn = new SqlConnection();
        string connStr = ConfigurationManager.ConnectionStrings["ApplicationServices"].ToString();
        conn.ConnectionString = connStr;
        conn.Open();

        string sql = "SELECT stat FROM NODE_PROPERTIES WHERE NodeID = " + Int32.Parse(nodeID.ToString());
        SqlCommand cmd = new SqlCommand(sql, conn);

        stat = Int32.Parse((cmd.ExecuteScalar().ToString()));
        conn.Close();
        return stat;
    }

我也将 asp:ScriptManager 添加到了 aspx 页面。无法为我的生活弄清楚为什么我会得到 NaN。我检查了 SQL 语句也没有问题。有人可以阐明我做错了什么吗?

回答:

正如建议的那样,我添加了一个回调函数。最终看起来像这样:

    setInterval(function () {
        newVal = 0;
        server_GetStats(1089, 1090);
    }, pollTime);

    function server_GetStats(nodeID) {
        PageMethods.getStats(nodeID, OnGetStatsSuccess, OnGetStatsFailure);
    }

    function OnGetStatsSuccess(result) {
        newVal = parseInt(result);
        rate = (newVal - val) / (pollTime / updateCounterTime);
    }

    function OnGetStatsFailure(result) {
        //do something when your server-side function fails to return the desired value
    }

代码隐藏保持不变。

4

2 回答 2

0

尝试遵循这个教程。另外,首先尝试从 web 方法返回一些固定值(也许 JavaScript 会返回 NaN,因为由于对数据库的查询而导致过期)。

于 2012-10-02T21:38:36.580 回答
0

When you are calling a PageMethod, it is getting called asynchronously. That means, when you call server_GetStats(1089), it is returning from that function before the PageMethod even completes. To get your code to work, you'll need to define a callback for your PageMethod call. Something along these lines:

var values = 0;

function myCallback(result) {
    values += parseInt(result);

    // Maybe call a function here that notifies/changes the UI.
}

function server_GetStats(nodeID) {
    PageMethods.getStats(nodeID, myCallback);
}

Reference: http://www.geekzilla.co.uk/View30F417D1-8E5B-4C03-99EB-379F167F26B6.htm

于 2012-10-02T21:47:40.047 回答