使用getJson()将Json字符串传递给JQuery
对于JSON
和jQuery
都是新手,但这是我想要做的 – 我将JSON
字符串作为更大的报表模型的一部分返回到我的网页,以便同时创建多个图表(使用jqPlot
)生成报告。
为了练习这些图表,我使用了以下教程 – 教程
这是本教程的jQuery
–
jQuery(document).ready(function() { urlDataJSON = '/Graph/HearthRateDataJSON'; $.getJSON(urlDataJSON, "", function(data) { var dataLines = []; var dataLabels = ""; $.each(data, function(entryindex, entry) { dataLines.push(entry['Serie']); dataLabels = dataLabels + entry['Name']; }); Plot(dataLines, dataLabels); }); }); function Plot(dataLines, dataLabels) { var line1 = "{ label: 'line1.0' }"; options = { legend: { show: true }, title: 'Heart rate overview', axesDefaults: { pad: 1 }, seriesDefaults: { showMarker: false, trendline: { show: false }, lineWidth: 3 }, axes: { yaxis: { min: 0, autoscale: true, label: 'HR[bpm]', labelRenderer: $.jqplot.CanvasAxisLabelRenderer }, xaxis: { autoscale: true, label: 'Time', labelRenderer: $.jqplot.CanvasAxisLabelRenderer } } }; //Data from database is already an array! plot = $.jqplot('chartdiv', dataLines, options); plot.redraw(); // gets rid of previous axis tick markers }
要检索JSON
数据,本教程使用getJson()方法指向链接。 我已准备好将JSON
字符串传递给jQuery
,例如
[ {"Name":"Patient","Serie":[[1,4],[2,25],[3,7],[4,14],[5,13]]}, {"Name":"Test","Serie":[[1,13],[2,5],[3,7],[4,20],[5,17]]} ]
在jqPlot
示例中,它们通过以下方式传递硬编码数据:
$(document).ready(function(){ var plot1 = $.jqplot ('chart1', [[3,7,9,1,4,6,8,2,5]]); });
但是,我自动生成的JSON
字符串有大括号等。有没有办法在不使用getJson方法的情况下将其传递给jQuery
?
编辑 – 饼图Jquery代码
$(document).ready(function () { var data4 = '[{ "Label": "Car", "Value": 9 },{ "Label": "Bus", "Value": 2 },{ "Label": "Train", "Value": 7 },{ "Label": "Plane", "Value": 8 },{ "Label": "Boat", "Value": 4 }]'; var data = $.parseJSON(data4); var plot1 = jQuery.jqplot('pieChart', [data], { seriesDefaults: { // Make this a pie chart. renderer: jQuery.jqplot.PieRenderer, rendererOptions: { // Put data labels on the pie slices. // By default, labels show the percentage of the slice. showDataLabels: true } }, legend: { show: true, location: 'e' } } ); });
您可以使用其他答案中提供的任何建议方法解析它,然后使用它。 或者只是简单地使用您拥有的JSON
数据,因为它是一个数组,并且{}
所有数据都被视为地图。 因此,您可以直接使用它们而无需进行任何解析, 就像我在此处提供的代码中所示的类似情况一样。
在提供的示例中,有一个名为json的变量编码的JSON
数据。
var json = [{ "Name": "Poll Results", "Serie": [[2, 5, 4], [4, 1, 7], [6, 3, 1], [3, 4, 2]]}]; var dataLines = json[0].Serie; var title = json[0].Name;
然后在最后dataLines
变量传递给图表。
编辑
在使用您提供的样本后,我得出以下结论。 显然,给定的数据不是jQuery的parseJSON方法可以使用的JSON格式。 但是当你进行字符串化时,它就能正
在将stringify应用于数据后,我的示例显示它正常工作。
我尝试将你的JSON转换为它的String等价物,将它包装在''
并且它有效。 所以答案很简单,使用parseJSON
方法你必须传递一个String而不是任何其他类型的Object。
使用parseJSON:
var plotline = $.parseJSON(jsonstring);
这将像getJSON一样工作,而不是获取url,你可以传递你的字符串。
您还可以使用浏览器的本机JSON.parse
方法