繁体   English   中英

来自Javascript的ASMX Web服务

[英]ASMX Web Service from Javascript

我制作了一个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); 
});

暂无
暂无

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

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