我正在做類似這樣的事情,但即使JSON看起來好像它會通過格式化正確但看到空值。爲了避免返回的整數值被包裹在雙引號中,我添加了absint
。任何想法,我哪裏錯了? PHP v.5.5.23。謝謝。jQuery Ajax JSON對象值爲NULL
class.php
public function stats($interval) {
global $wpdb;
$title = $this->title;
if (is_object($wpdb) && is_a($wpdb, 'wpdb')) {
$totals = $wpdb->get_results("
SELECT * FROM wp_video_stats WHERE vid_title = '$title' AND DATE(updated) = DATE_SUB(DATE(NOW()), INTERVAL '$interval' DAY)");
}
foreach ($totals as $row) {
$days = absint($row->days);
$weeks = absint($row->weeks);
$months = absint($row->months);
}
return array(
'title'=>$title,
'days'=>$days,
'weeks'=>$weeks,
'months'=>$months
);
}
$array = $results->stats(2);
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
header('Content-type: application/json');
echo json_encode($array);
exit();
}
page.php文件
<script>
$.ajax({
url : '/class.php',
type : 'POST',
dataType : 'json',
success : function (data) {
console.log(data);
},
error : function() {
console.log("error");
}
})
</script>
JSON
{
"title":"title_test",
"days":217,
"weeks":37,
"months":3
}
的console.log
Object {title: "title_test", days: null, weeks: null, months: null}
不在ajax中發佈任何數據 – charlietfl
'$ interval'是傳遞給查詢的參數。 – Jamie
您還期待多少結果?如果不止一個會覆蓋循環中的變量。做'$ totals'轉儲並在你的控制檯中看到它......'echo json_encode($ totals);退出;' – charlietfl