c# - 来自 Javascript 的 ASMX Web 服务

标签 c# javascript web-services asmx

我创建了一个 Web 服务,其中有一个函数可以计算我的 SQL 数据库中的一些数据。这是我的 WebService.asmx 的代码:

[System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
{

    [WebMethod]
    public int SalesNumberMonth(int i)
    {
        int total = 0;
        SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Sql"].ConnectionString);
        try
        {
            string request = "SELECT * FROM sales_Ventes V INNER JOIN sys_AnneesFiscales A ON V.AnneeFiscale = A.Code INNER JOIN sys_Mois M ON V.Mois = M.Code WHERE M.Code='" + i + "'" + " AND Active = 'true'";
            connection.Open();
            SqlCommand Req = new SqlCommand(request, connection);

            SqlDataReader Reader = Req.ExecuteReader();
            while (Reader.Read())
            {
                total++;
            }
            Reader.Close();
        }
        catch
        {

        }
        connection.Close();
        return total;
    }
}

这是我的 script.js :

var sin = [], cos = [];
for (var i = 1; i < 13; i += 1) {
    GestionPro.WebService1.SalesNumberMonth(i,  function (e) { sin.push([i, e]); }  ,function (response) { alert(response); }  );
    cos.push([i, 2]);
}
var plot = $.plot($("#mws-test-chart"),
       [{ data: sin, label: "Sin(x)²", color: "#eeeeee" }, { data: cos, label: "Cos(x)", color: "#c5d52b"}], {
           series: {
               lines: { show: true },
               points: { show: true }
           },
           grid: { hoverable: true, clickable: true }
       });

我的问题在这一行:

GestionPro.WebService1.SalesNumberMonth(i,  function (e) { sin.push([i, e]); }  ,function (response) { alert(response); }  );

当我交换这两个函数时,警报显示得很好,但按此顺序我无法在 sin[] 中添加我的函数值。我应该错过一些东西,但不知道是什么......

最佳答案

您的代码有很多问题:

  • 您正在 for 循环中触发 AJAX 请求。触发将返回整个结果的单个 AJAX 请求要好得多。发送更少的请求来发送更多的数据总是比发送大量的小 AJAX 请求更好
  • 您正在使用 SELECT * 然后在循环中计算客户端代码,而不是使用 COUNT SQL 聚合函数
  • 您没有正确处理任何 IDisposable 资源,例如数据库连接、命令和读取器
  • 您正在使用字符串连接来构建 SQL 查询,而不是使用参数化查询
  • 您没有考虑到 AJAX 的异步特性

提到的问题,让我们从修复它们开始。

让我们首先修复服务器端代码:

[System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
{
    [WebMethod]
    public int[] SalesNumbersMonths(int[] months)
    {
        // Could use LINQ instead but since I don't know which version
        // of the framework you are using I am providing the naive approach
        // here. Also the fact that you are using ASMX web services which are
        // a completely obsolete technology today makes me think that you probably
        // are using something pre .NET 3.0
        List<int> result = new List<int>();
        foreach (var month in months)
        {
            result.Add(SalesNumberMonth(month));
        }
        return result.ToArray();
    }


    [WebMethod]
    public int SalesNumberMonth(int i)
    {
        using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Sql"].ConnectionString))
        using (SqlCommand cmd = conn.CreateCommand())
        {
            conn.Open();
            cmd.CommandText = "SELECT COUNT(*) FROM sales_Ventes V INNER JOIN sys_AnneesFiscales A ON V.AnneeFiscale = A.Code INNER JOIN sys_Mois M ON V.Mois = M.Code WHERE M.Code=@Code AND Active = 'true'";  
            cmd.Parameters.AddWithValue("@Code", i);
            return (int)cmd.ExecuteScalar();
        }
    }
}

好的,您现在会注意到我添加的新方法,它允许计算几个月的总计并将它们作为整数数组返回,以避免在无意义的 AJAX 请求中浪费带宽。

现在让我们修复您的客户端代码:

var months = [];

for (var i = 1; i < 13; i += 1) {
    months.push(i);
}

GestionPro.WebService1.SalesNumbersMonths(months, function (e) { 
    // and once the web service succeeds in the AJAX request we could build the chart:
    var sin = [],
        cos = [];

    for (var i = 0; i < e.length; i++) {
        cos.push([i, 2]);
        sin.push([i, e[i]]);
    }

    var chart = $('#mws-test-chart'),
    var data = [
        { data: sin, label: 'Sin(x)²', color: '#eeeeee' }, 
        { data: cos, label: 'Cos(x)', color: '#c5d52b' }
    ];

    var series = { 
        series: {
            lines: { show: true },
            points: { show: true }
        }
    };

    var plot = $.plot(
        chart, 
        data, 
        series, 
        grid: { hoverable: true, clickable: true }
    );

    // TODO: do something with the plot

}, function (response) { 
    // that's the error handler
    alert(response); 
});

关于c# - 来自 Javascript 的 ASMX Web 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11328923/

相关文章:

web-services - 在域数据错误时返回哪个 HTTP 状态?

c# - 在 WP7 的 silverlight 中删除图像源

c# - 不声明外键的导航属性

javascript - 让 iframe 适合 Android 手机上的整个页面

javascript - jQuery 中的水平选择 slider

javascript - 在 cloudflare 工作人员中从一个域重定向到另一个域不起作用

c# - 异步/等待多核

c# - 无法看到 Entity Framework 中创建的数据库

Android 应用程序开发和 Web 服务器交互

python RESTful 网络服务框架 : roll my own or is there a recommended library?