ASMX Web Service from Javascript

ASMX Web Service from Javascript

本文关键字:Javascript from Service Web ASMX      更新时间:2023-09-26

我做了一个 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;
    }
}

这是我的脚本.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 聚合函数
  • 您没有正确处置任何可识别的资源,例如数据库连接、命令和读取器
  • 您正在使用字符串串联来构建 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); 
});