我正在尝试在Wordpress中测试自定义REST路由。我在自己的插件文件中有以下PHP:
add_action( 'rest_api_init', function() {
register_rest_route('tuck-api/v1', '/send_campaign', array(
'methods' => 'POST',
'callback' => 'campaign_email_route'
));
});
function campaign_email_route( WP_REST_Request $request ) {
return json_encode($request->get_json_params());
}
现在我只想让它回应请求体作为测试。我通过管理面板中的插件使用以下jQuery AJAX请求来调用它:
$.ajax({
type: 'POST',
url: '/wp-json/tuck-api/v1/send_campaign',
contentType: 'application/json',
data: {
recipient: $('.email-recipient').val(),
campaign_id: campaignList[i].id.toString()
},
success: function(res) {
console.log(res);
}
});
成功回调中的console.log是吐出400 Bad Request错误的原因。
答案 0 :(得分:1)
试试此代码
Class SendCampaign{
public function __construct() {
add_action( 'rest_api_init', array( $this, 'campaign_init_rest_api') );
}
public function campaign_init_rest_api()
{
register_rest_route('tuck-api/v1', '/send_campaign', array(
'methods' => 'POST',
'callback' => array( $this, 'campaign_email_route')
));
}
function campaign_email_route($data ) {
$request = $data['data'];
echo json_encode($data['data']);
exit;
}
}
$SendCampaign = new SendCampaign();
<script>
jQuery.ajax({
type: 'POST',
url: '/wp-json/tuck-api/v1/send_campaign',
// contentType: 'application/json',
data: {data:{
recipient: jQuery('.email-recipient').val(),
campaign_id: campaignList[i].id.toString()}
},
success: function(res) {
console.log(res);
}
});
</script>