Ajax data to FLOT chart in correct format?

2019-01-27 01:40发布

I know there are several posts about this but I think I'm missing something. I'm returning the data below in an ajax call but it doesn't seem to be in the right format for FLOT. Is there a better format to return the data in or what should be changed for FLOT to recognize it? TIA

<script type="text/javascript">
     $(document).ready(function() {
         // Add the page method call as an onclick handler for the div.
         $("#Result").click(function() {
             $.ajax({
                 type: "POST",
                 url: "WebTest.aspx/GetData",
                 data: "{}",
                 contentType: "application/json; charset=utf-8",
                 dataType: "json",
                 success: function(msg) {
                     // Replace the div's content with the page method's return.

                     var jsObj = []
                     jsObj.push($.parseJSON(msg.d));

                     $.plot($("#Result"), jsObj, {
                         grid: {
                             backgroundColor: "#E5E5E5",

                             mouseActiveRadius: 20
                         }


                     }
                 );
                 }
             });
         });
     });
</script>


[WebMethod]
public static string GetData()
{

    DataLines dataLine1 = new DataLines();
    DataLines dataLine2 = new DataLines();


    int[] lineA_Point1 = new int[] { 4, 6 };
    int[] lineA_Point2 = new int[] { 2, 10};

    List<int[]> dataA = new List<int[]>();
    dataA.Add(lineA_Point1);
    dataA.Add(lineA_Point2);

    dataLine1.data = dataA;
    dataLine1.label = "DataLine1";

    JavaScriptSerializer js = new JavaScriptSerializer();

    string Line1 = js.Serialize(dataLine1);

    return Line1;
}

标签: c# ajax flot
1条回答
乱世女痞
2楼-- · 2019-01-27 02:16

1.) Convert the JSON string back to a javascript object in your javascript:

var jsObj = $.parseJSON(d); // using jquery method

2.) In your GetData method, your

dataLine1.data = "[[1356328800000,5],[1356933600000,3]]";

isn't going to work. That will make your data element a string in the JSON instead of a javascript array. It would be best to fix this in your WebMethod:

DataLines dataLine1 = new DataLines();
dataLine1.data = new List<int[]>();
dataLine1.data.Add(new int[] {1356328800000,5});
dataLine1.data.Add(new int[] {1356933600000,3});

That's totally untested (I've never used the JavaScriptSerializer before, but similar code works with the ServiceStack serializer.

查看更多
登录 后发表回答