javascript在调用服务器端函数时返回NaN

时间:2012-10-02 21:18:32

标签: javascript asp.net server-side nan pagemethods

我有以下试图调用服务器端功能的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;
    }

我也在aspx页面中添加了asp:ScriptManager。不能为我的生活弄清楚为什么我会得到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
    }

代码隐藏保持不变。

2 个答案:

答案 0 :(得分:0)

尝试关注this tuto。此外,首先尝试从web方法返回一些固定值(也许JavaScript返回NaN,因为查询到数据库的过期时间。)

答案 1 :(得分:0)

当您调用PageMethod时,它将被异步调用。这意味着,当您调用server_GetStats(1089)时,它会在PageMethod完成之前从该函数返回。要使代码生效,您需要为PageMethod调用定义回调。这些方面的东西:

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);
}

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

相关问题