问题
I have the following jQuery code:
$(document).ready(function () {
var group = 'test';
$.ajax({
type: "POST",
async: false,
url: "/validate.asmx/GetGraphData",
contentType: "application/json;",
data: "{'groupBy': '" + group + "'}",
dataType: 'json',
success: function (data) {
Plot(data.d);
}
});
});
function Plot(dataIn) {
alert(dataIn);
$.jqplot('chartcontainer', [[[ 'test1', 1 ], [ 'test2', 5]]],
{
seriesDefaults: {
renderer: $.jqplot.PieRenderer,
rendererOptions: {
showDataLabels: true
}
},
legend: { show: true, location: 'e' }
}
);
}
The webmethod (after cutting it for testing) looks like this:
[WebMethod]
public string GetGraphData(string groupBy)
{
PaymentModelDataContext db = new PaymentModelDataContext();
var q = from Event in db.TrackingEvents
group Event by Event.campaignID;
//string returnJSON;
//string returnJSON = "[";
//foreach (var grp in q)
//{
// returnJSON += "['" + grp.Key + "'," + grp.Count() + "],";
//}
//returnJSON += "]";
//var ser = new JavaScriptSerializer();
//returnJSON = ser.Serialize(q);
//return returnJSON;
return "[['test1' , 1],['test2' , 5]]";
}
If I take the same string I return here and put it as text in the jquery code, the plot is shown. I put an alert in the plot function, and the data is as I sent it. Any ideas?
Thank you!
回答1:
use the dataRenderer
$(document).ready(function(){
var ajaxDataRenderer = function(url, plot) {
var ret = null;
$.ajax({
// have to use synchronous here, else returns before data is fetched
async: false,
url: url,
dataType:'json',
success: function(data) {
ret = data;
}
});
return ret;
};
var jsonurl = "/validate.asmx/GetGraphData";
plo12 = $.jqplot('chart2', jsonurl,{
title: 'AJAX JSON Data Renderer',
dataRenderer: ajaxDataRenderer,
seriesDefaults: {
renderer: $.jqplot.PieRenderer,
rendererOptions: {
showDataLabels: true
}
},
legend: { show: true, location: 'e' }
});
});
回答2:
Putting ajax data to jqPlot dataRenderer is one option. But it will also work at the way you choose.
Make sure, that the data is not processed as string.
if your data is "[['test1' , 1],['test2' , 5]]"
than
arr=eval("[['test1' , 1],['test2' , 5]]")
should generate an array from your data.
You will see the difference, if you use console.warn("[['test1' , 1],['test2' , 5]]");
and console.warn(arr);
on the firebug console.
来源:https://stackoverflow.com/questions/7013650/jqplot-does-not-show-ajax-data