如何传递从webservice返回的json数据到D3.json(...)? [英] How can I pass json data returned from a webservice into D3.json(...)?

查看:157
本文介绍了如何传递从webservice返回的json数据到D3.json(...)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

感谢您的帮助!我能够成功地构建我的webservice和NVD3.js堆积面积图。但是,我一直在努力,没有任何成功将json数据从我的webservice传递到我的NVD3.js图。在我的webform上,我为一个间隔选择两个日期,然后单击go按钮。



我觉得很明显,我失踪了。如果不可能,是否有一种方法来保存从我的webservice返回的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,
方法:post,
data:{
startDate:startDate,
endDate:endDate
},
dataType:json,
contentType:application / json,
success:function(data){
//这是我尝试传递我的json数据
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>

这是我的网络服务:

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

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

//将SQL参数与webmethod参数链接
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();

//获取时间(毫秒)
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;

//声明临时字典以存储列表
字典< string,List< long []> temp = new Dictionary< string,List< long []>>();
string [] buildings = {SSB,GEN,LYM,LUD,GCC,MAC,MMB};

//创建构建列表并用单独的日期和默认值初始化它们0
foreach(建筑物中的字符串构建){
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())
{

//从dateTime2中删除时间,并为适当的日期分配合计
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;
}
//将所有keyValue对象添加到主列表
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();

//将列表对象序列化为JSON数组并写入响应流
string ss = js.Serialize(master);
return ss;

}

这里是从我的web服务返回的json的结构。我在脚本标签中获取文件:



解决方案

您不需要同时调用 $。ajax d3.json ,这些方法做同样的事情,我只使用:

  d3.json(dataWebService.asmx / getCasesForDateInterval函数(错误,数据){

其次,如果你坚持使用 $ .ajax 调用你的方法实际上是一个 GET 而不是 POST ,因为你可以导航到



第三,你最大的问题是,你的web服务没有返回JSON,它返回一个用XML包装的JSON字符串(这是默认的对于较旧的基于Microsoft SOAP的Web服务)。您应该能够通过将此属性添加到您的方法的顶部来强制JSON:

  [ScriptMethod(UseHttpGet = true,ResponseFormat = ResponseFormat.Json)] 
public string getTotalForDateInterval(string startDate,string endDate)
$ p>

Thank you for your help so far! I was able to successfully build my webservice and NVD3.js stacked area chart. However, I have been struggling without any success in passing json data from my webservice into my NVD3.js graph. On my webform, I select two dates for an interval and click a "go" button.

I feel that it is something obvious that I am missing. If not possible, is there a way of saving the json data returned from my webservice into a regular file (e.g. myFile.json), so that I can pass it in my graph? Thank you very much for your help! Here is my latest attempt:

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

Here is my webservice:

    [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;

}

Here is the structure of the json returned from my webservice. I get the file within script tags:

解决方案

You don't need to call both $.ajax and d3.json, these methods do the same thing and I would just use:

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

Second, if you stick with the $.ajax call your method is actually a GET not a POST since you can navigate to it in a web-browser.

Third, and your biggest problem, your web service is not returning JSON. It's returning a JSON string wrapped in XML (this is the default for older Microsoft SOAP based web services). You should be able to force JSON by adding this attribute to top of your methods:

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

这篇关于如何传递从webservice返回的json数据到D3.json(...)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆