2016-12-28 162 views
0
[System.Web.Services.WebMethod] 
public Array loaddata()  
string sql = "SELECT Name,Time,Inuse FROM table4";  
using (SqlConnection Connection = new SqlConnection((@"Data Source")))  
{  
    using (SqlCommand myCommand = new SqlCommand(sql, Connection))  
    {  
     Connection.Open();  
     using (SqlDataReader myReader = myCommand.ExecuteReader())  
     {  
      DataTable dt = new DataTable();  
      dt.Load(myReader);  
      Connection.Close();  
      DataView dv = new DataView(dt);  
      dv.RowFilter = (("Name='ACVX'"));  
      var tableEnumerable = dv.ToTable().AsEnumerable();  
      var tableArray = tableEnumerable.ToArray();  
      return tableArray ; 
     }  
    }  
}  

//Front End 

<html> 
<head/> 
<script> 
PageMethods.loaddata(LoadSucc, LoadFail); 
      function LoadSucc(obj) //obj is array returned from back end{obj-tablearray] 
      { 
       var goog = []; 
       goog = Object.values(obj); 
      //I want load the obj into my array goog. 
      } 

      function LoadFail() { 
       alert("Data missing"); 
      } 
script> 
<body/> 
<html> 

我想加載我的數據表內容到數組,並使用頁面方法將數組返回到前​​端。我嘗試了一些東西,但它不會工作。我的代碼有什麼問題?
建議我的一些想法從後端到前端返回數組

+0

有你在調試控制檯鉻在功能obj的?它是空的嗎?有時它會在數據字段中包裝響應,因此您必須執行類似obj.data的操作.. –

回答

0

嗨嘗試調用使用jQuery AJAX funtion這樣您的WebMethod:

<html> 
<head/> 
<script> 



     $.ajax({ 
           type: "POST", 
           url: "/yourpagename.aspx/loaddata", 
           data: "", 
           contentType: "application/json; charset=utf-8", 
           dataType: "json", 
           success: function (data) { 
            var dataArray = $.map(data, function (item) { 
             return item; 
            }); 
            alert(dataArray); 
            console.log(dataArray); 
           }, 
           error: function (data) { 
            alert("ajax error " + data); 
           } 
          }); 

script> 
<body/> 
<html> 
+0

對不起,我無法理解這個概念。請您再解釋一次嗎? – monica

+0

你試圖調用你的後端服務不是與Ajax和JQuery(JavaScript)...我向你建議(我記得當我與WebMethod和WebForms合作)是嘗試調用這些WebMethod服務(在後端)從一個JavaScript前端..可能與Jquery –

+0

感謝您的迴應。 – monica