好的,我几乎在这里读过关于ajax,php以及我能找到的所有内容的每一篇文章。我想做的是
获取我从数据库中提取的数组并将其放入chart.js脚本中。我知道我在firebug中检查后正确地提取数据。它正好通过标题。我的问题是,一旦我收回它,我想要a)将它放入变量或2)只需替换chart.js脚本中的数据集。
我会粘贴脚本并提供尽可能多的指导。
var cigarData = $.ajax({
data: {cigar: sCigar, calc: "cigar"},
type: "POST",
url: "http://www.blah",
dataType:"json",
async: false,
success:function(data) {
// This outputs the result of the ajax request
console.log(data);
}
}).responseText;
var radarChartData = {
labels : ["Caramel","Creamy","Earthy","Floral","Fruity","Spicy","Sweet","Woody"],
datasets : [
{
fillColor : "rgba(228,154,7,0.5)",
strokeColor : "rgba(228,154,7,1)",
pointColor : "rgba(228,154,7,1)",
pointStrokeColor : "#fff",
data : [cigarData]//Where I want the data to be
}
]
任何帮助都会很棒。我很感激大家。我会在上午回来回答任何问题。
我已经使用下面的答案编辑了我的代码:
$('#cigar').change(function (event) {
var sCigar = $("#cigar").val();
var cigarData = $.ajax({
data: {cigar: sCigar, calc: "cigar"},
type: "POST",
url: "http://www.blah.com",
dataType:"json",
async: false,
success:function(data) {
//update chart here
updateChartData(data);
}
}).responseText;
//wrap chart refresh code as function
function updateChartData(data){
var cigarData=data;
var radarChartData = {
labels : ["Caramel","Creamy","Earthy","Floral","Fruity","Spicy","Sweet","Woody"],
datasets : [
{
fillColor : "rgba(228,154,7,0.5)",
strokeColor : "rgba(228,154,7,1)",
pointColor : "rgba(228,154,7,1)",
pointStrokeColor : "#fff",
data : [cigarData] //Where I want the data to be
}
]
}
};
var myRadar = new Chart(document.getElementById("cigarCanvas").getContext("2d")).Radar(radarChartData,{scaleShowLabels : false, pointLabelFontSize : 10});
});
});
现在每次都在重新绘制地图,但数据点没有变化。就像它不断将相同的数据集拉入地图一样。我正在查看标题,每次更改选择时它都会传递不同的信息,但它并没有将它放入[cigarData]中。有什么东西让我在这里不见了吗? var myRadar是否需要在它上面的函数内部才能正确地提取数据?我只是不确定每个函数需要通过它们正确传递信息的确切布局。感谢您迄今为止的所有帮助,你们真棒。
答案 0 :(得分:1)
Ajax调用是异步的,这意味着在从服务器收到响应后执行回调,而不是按顺序写入代码。
这应该是正确的方法。
var cigarData = $.ajax({
data: {cigar: sCigar, calc: "cigar"},
type: "POST",
url: "http://www.blah",
dataType:"json",
async: false,
success:function(data) {
//update chart here
updateChartData(data);
}
}).responseText;
//wrap chart refresh code as function
function updateChartData(data){
var cigarData=data;
var radarChartData = {
labels : ["Caramel","Creamy","Earthy","Floral","Fruity","Spicy","Sweet","Woody"],
datasets : [
{
fillColor : "rgba(228,154,7,0.5)",
strokeColor : "rgba(228,154,7,1)",
pointColor : "rgba(228,154,7,1)",
pointStrokeColor : "#fff",
data : [cigarData] //Where I want the data to be
}
]
}