2016-07-30 84 views
1

感謝您的幫助!我能夠成功地構建我的webservice和NVD3.js堆積區域圖表。然而,我一直在努力將json數據從我的webservice傳遞到我的NVD3.js圖表​​中。在我的網絡表格中,我選擇了兩個日期間隔並點擊「去」按鈕。如何將從Web服務返回的Json數據傳遞到D3.json(...)?

我覺得這是顯而易見的,我失蹤了。如果不可能,有沒有辦法將從我的web服務返回的json數據保存到常規文件(例如myFile.json)中,以便我可以將它傳遞到我的圖中?非常感謝您的幫助!這裏是我的最新嘗試:

<script type="text/javascript"> 
     $(document).ready(function(){ 
      $("#btGO").click(function(){ 
       var startDate = $("#startDate").val(); 
       var endDate = $("#endDate").val(); 

       $.ajax({ 
        url: "dataWebService.asmx/getCasesForDateInterval", 
        method: "post", 
        data: { 
         startDate: startDate, 
         endDate: endDate 
        }, 
        dataType: "json", 
        contentType: "application/json", 
        success: function (data) { 
         //This is where I attempt to pass my json data 
         d3.json(data, function (error, data) { 
          nv.addGraph(function() { 
           var chart = nv.models.stackedAreaChart() 
               .x(function (d) { return d[0] }) 
               .y(function (d) { return d[1] }) 
               .clipEdge(true) 
               .useInteractiveGuideline(true); 

           chart._options.controlOptions = ['Expanded', 'Stacked']; 

           chart.xAxis 
            .showMaxMin(true) 
            .tickFormat(function (d) { return d3.time.format('%x')(new Date(d)) }); 

           chart.yAxis 
            .tickFormat(d3.format(',.0f')); 

           d3.select('#chart svg') 
            .datum(data) 
            .transition().duration(500).call(chart); 

           nv.utils.windowResize(chart.update); 

           return chart; 
          }); 
         }); 
        } 
       }); 

      }); 
     }); 
    </script> 

這裏是我的web服務:

[WebMethod] 
    public string getTotalForDateInterval(string startDate, string endDate) 
    { 
    string cs = ConfigurationManager.ConnectionStrings["vetDatabase_Wizard"].ConnectionString; 
    List<keyValues> master = new List<keyValues>(); 

    using (SqlConnection con = new SqlConnection(cs)) 
    { 
     SqlCommand cmd = new SqlCommand("sp_CountAndGroupByDate", con); 
     cmd.CommandType = CommandType.StoredProcedure; 

     //Linking SQL parameters with webmethod parameters 
     SqlParameter param1 = new SqlParameter() 
     { 
      ParameterName = "@startDate", 
      Value = startDate 
     }; 

     SqlParameter param2 = new SqlParameter() 
     { 
      ParameterName = "@endDate", 
      Value = endDate 
     }; 

     cmd.Parameters.Add(param1); 
     cmd.Parameters.Add(param2); 
     con.Open(); 

     //Get time in milliseconds 
     DateTime start = DateTime.ParseExact(startDate, "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture); 
     DateTime end = DateTime.ParseExact(endDate, "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture); 
     DateTime utime = DateTime.ParseExact("1970-01-01", "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture); 

     long startMilliseconds = (long)((start - utime).TotalMilliseconds); 
     long endMilliseconds = (long)((end - utime).TotalMilliseconds); 
     const long oneDayInMilliseconds = 86400000; 

     //Declare temp dictionary to store the lists 
     Dictionary<string, List<long[]>> temp = new Dictionary<string, List<long[]>>(); 
     string[] buildings = { "SSB", "GEN", "LYM", "LUD", "GCC", "MAC", "MMB" }; 

     //Create building lists and initialize them with individual days and the default value of 0 
     foreach (string building in buildings){ 
      temp.Add(building, new List<long[]>()); 
      for (long j = startMilliseconds; j <= endMilliseconds; j = j + oneDayInMilliseconds){ 
       long[] timeTotal = { j, 0 }; 
       temp[building].Add(timeTotal); 
      } 
     } 

     SqlDataReader rdr = cmd.ExecuteReader(); 
     while (rdr.Read()) 
     { 

      //Remove time from dateTime2 and assign totals for appropriate date 
      string s = (rdr["dateOpened"].ToString()).Substring(0, 10); 
      DateTime dateOpened = DateTime.ParseExact(s, "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture); 
      long time = (long)((dateOpened - utime).TotalMilliseconds); 
      long total = (long)Convert.ToInt32(rdr["total"]); 

      string buildingName = rdr["building"].ToString(); 
      int index = temp[buildingName].FindIndex(r => r[0].Equals(time)); 
      temp[buildingName][index][1] = total; 
     } 
      //add all the keyValue objects to master list 
      for (int i = 0; i < buildings.Length; i++) 
      { 
       keyValues kv = new keyValues(); 
       kv.key = buildings[i]; 
       kv.values = temp[kv.key]; 
       master.Add(kv); 
      } 

     } 
    JavaScriptSerializer js = new JavaScriptSerializer(); 

    //Serialize list object into a JSON array and write in into the response stream 
    string ss = js.Serialize(master); 
    return ss; 

} 

這裏是JSON的結構從我的web服務返回。我得到的腳本標記內的文件:

enter image description here

+0

一句忠告:你是在這個問題上開重複的問題很多。其中一些人提供了您尚未回覆的評論和答案。這非常反對堆棧溢出禮節,並會讓用戶不願意幫助你。例如,下面給出的答案[重複一個答案](http://stackoverflow.com/a/37759986/16363)@cyril在一個月前給了你。 – Mark

+0

@ Mark Hi Mark!謝謝您的回答。我同意你的看法:我發佈了非常相似/重複的問題,但沒有回覆,而且看起來很糟糕。這些解決方案沒有起作用,因爲我使用Google的檢查員剛剛拿到了一些無關的錯誤。不過,我應該回復他們。有時候我很專注,以至於對別人不尊重。我爲此道歉。 – Johnathan

回答

1

你並不需要通話雙方$.ajaxd3.json,這些方法做同樣的事情,我只想用:

d3.json("dataWebService.asmx/getCasesForDateInterval", function (error, data) { 

其次,如果您堅持使用$.ajax,請致電您的方法實際上是GET而不是POST,因爲您可以在網絡瀏覽器中導航到它。

三,你最大的問題是,你的web服務沒有返回JSON。它返回一個包裝在XML中的JSON字符串(這是較早的基於Microsoft SOAP的Web服務的默認值)。您應該能夠通過添加以下屬性來頂你的方法來強制JSON:

[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)] 
public string getTotalForDateInterval(string startDate, string endDate) 
相關問題