认真请教个问题!折磨了我几个通宵!没搞定!
作为一名英语老师,主要是因为wordpress而热爱上php,css,js等程序,属于瞎折腾,纯属业余爱好。
目标:用页面引用js,js读取wordpress的REST API,获得最新评论列表,显示在前台。
js需要的数据格式如下:
var data = [
{href : '#',text : '测试文本'},
]
而且直接在js里加入上面这段,前端就能正常显示。
查阅百度,利用下面的代码,好像也可以读取wordpress的API:
$.ajax({
type: "POST",
data: {},
url: 'http://localhost/wp-json/myapi/test', //api地址
success: function(data) {
// 数据初始化
var Obj = $('body').barrage({
data : data, //数据列表
row : 2, //显示行数,初始为5
time : 3000, //间隔时间,初始为1500
gap : 15, //每一个的间隙,初始为15
position : 'fixed', //绝对定位,初始为
direction : 'bottom right', //方向,初始为bottom right
ismoseoverclose : true, //悬浮是否停止,初始为true
height : 30, //设置单个div的高度,初始为30
})
Obj.start();
}
});
于是,我就在主题的functions.php里自定义了API测试接口,代码如下:
//自定义REST API接口
add_action( 'rest_api_init', 'popup_comments_rest_register_route' );
function popup_comments_rest_register_route() {
register_rest_route( 'a', 'b', [
'methods' => 'POST',
'callback' => 'popup_comments'
] );
}
function popup_comments() {
$out = array(
'href' => '#',
'text' => '测试文本',
);
//print json_encode($out);
//return $out;
//print json_encode(array('status'=>200,'href'=>$out,'text'=>$out));
//unset($out);
//exit;
//die();
echo $out;
wp_die();
}
在网页上,访问http://localhost/wp-json/myapi/test
用'methods' => 'GET', 可以输出在页面上显示 {href : '#',text : '测试文本'}
然后修改回 'methods' => 'POST',再测试前端,还是不能显示!
个人感觉是REST API接口没配置好,或者$.AJAX没用好?
麻烦各位,给以指导,给个启发!感谢!
另:用wordpress默认的API链接,V2和V1版本有啥不同,用默认的API怎么能保持数据结构只要href和text
http://localhost/wp-json/wp/v2/comments可以拉出很多内容
http://localhost/wp-json/b2/v1/getnewcomments默认显示没有route