我正在做类似这样的事情,但是即使JSON看起来像是正确的格式化,也会获得空值。为了避免返回的整数值被双引号括起来,我添加了absint
。知道我哪里错了吗? PHP v.5.5.23。感谢。
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}
答案 0 :(得分:1)
我最终想出来了。我的自定义页面中需要引用wp-load.php
。值得庆幸的是,我发现这篇文章Cant access wp-load.php dynamically显示了一种方法,可以在本地包含对我有用的文件。
$root = dirname(dirname(dirname(dirname(__FILE__))));
if (file_exists($root.'/wp-load.php')) {
require_once($root.'/wp-load.php');
} else {
require_once($root.'/wp-config.php');
}