通过 AJAX 从 PHP 传递 JSON 数据时出现莫里斯图表错误
Morris chart error when passing JSON data from PHP via AJAX
我通过 json_encode
使用以下代码从数据库中获取数据:
$orderList = $this->Retrieve->retrieve_data('*');
$data = array();
foreach ($orderList as $order) {
array_push($data, array(
'd' => $order['createdDate'],
'sales' => $order['order_price']
));
}
echo json_encode(array('data' => $data));
这是输出:
{"data":[{"d":"2015-09-26","sales":"0.00"},{"d":"2015-09-26","sales":"200.00"},{"d":"2015-09-26","sales":"45.00"},{"d":"2015-09-26","sales":"1500.00"}]}
这是我的 Javascript 代码:
$.ajax({
url: baseURL + '/Memberinfo/getGraphicalActivity',
cache: false,
type: "POST",
data: {patientFK: $("#patientFK").val()},
dataType: "json",
timeout:3000,
success : function (data) {
memberArea = new Morris.Line({
element: 'line-chart-memberInfo',
data: data,
xkey: 'd',
ykeys: ['sales'],
labels: ['Sales'],
smooth: false,
parseTime:false,
resize: true
});
},
error : function (xmlHttpRequest, textStatus, errorThrown) {
alert("Error " + errorThrown);
if(textStatus==='timeout')
alert("request timed out");
}
});
它returns这个错误:
Uncaught TypeError: Cannot read property 'x' of undefined
为什么会这样?
问题在于我如何在 PHP 中构建 JSON 数据。这是代码:
foreach ($orderList as $order) {
$arr[] = array(
'd' => ''.$order['createdDate'].'',
'sales' => ''.$order['order_price'].'',
);
}
echo json_encode($arr);
我通过 json_encode
使用以下代码从数据库中获取数据:
$orderList = $this->Retrieve->retrieve_data('*');
$data = array();
foreach ($orderList as $order) {
array_push($data, array(
'd' => $order['createdDate'],
'sales' => $order['order_price']
));
}
echo json_encode(array('data' => $data));
这是输出:
{"data":[{"d":"2015-09-26","sales":"0.00"},{"d":"2015-09-26","sales":"200.00"},{"d":"2015-09-26","sales":"45.00"},{"d":"2015-09-26","sales":"1500.00"}]}
这是我的 Javascript 代码:
$.ajax({
url: baseURL + '/Memberinfo/getGraphicalActivity',
cache: false,
type: "POST",
data: {patientFK: $("#patientFK").val()},
dataType: "json",
timeout:3000,
success : function (data) {
memberArea = new Morris.Line({
element: 'line-chart-memberInfo',
data: data,
xkey: 'd',
ykeys: ['sales'],
labels: ['Sales'],
smooth: false,
parseTime:false,
resize: true
});
},
error : function (xmlHttpRequest, textStatus, errorThrown) {
alert("Error " + errorThrown);
if(textStatus==='timeout')
alert("request timed out");
}
});
它returns这个错误:
Uncaught TypeError: Cannot read property 'x' of undefined
为什么会这样?
问题在于我如何在 PHP 中构建 JSON 数据。这是代码:
foreach ($orderList as $order) {
$arr[] = array(
'd' => ''.$order['createdDate'].'',
'sales' => ''.$order['order_price'].'',
);
}
echo json_encode($arr);