簡體   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