[英]Can't send data from API to AJAX using POST method
我有一个很奇怪的问题。 我的ajax请求只返回没有实际值的字符串/,除非类ID在哪里,只有在那里检索postID /。 我不确定问题出在哪里,但这是我的代码:
JQUERY:
var roomID = jQuery(this).closest('li').attr('id');
jQuery.ajax({
url: '/wp-json/api/hotelRooms',
data: {
'post_id':roomID
},
type: 'POST',
dataType: 'json',
success: function (data) {
jQuery(".rooms-popups-container").empty();
jQuery(".rooms-popups-container").append(data);
console.log(data);
},
error: function hotelRooms(data) {
console.log('Error:', data);
}
});
PHP:/不发布所有代码,只是其中的一小部分
add_action( 'rest_api_init', function (){
register_rest_route( 'api', '/hotelRooms', array(
'methods' => 'POST',
'callback' => 'hotelRooms',
));
});
function hotelRooms($returndata){
$postID = $_POST['post_id'];
$posttitle = get_the_title($postID);
$postcontent = get_post_field('post_content', $postID);
$galleries = get_post_meta( $postID, '_hb_gallery', true );
$returndata = "";
$returndata .= '<div class="hb_single_room room-popup" id="popup-room-'.$postID.'">
<div class="summary entry-summary">
<div class="title">
<h4>
<a href="#">'. $posttitle .'</a>
<img class="close-room-popup" room_id="'.$postID.'" alt="x" src="https://www.micasas.it/wp-content/uploads/2018/03/x.png">
</h4>
</div>';
return $returndata;
}
在POSTMAN中,它返回实际值以及我需要的所有内容-> http://prntscr.com/me517n,但是在Jquery中,它仅返回部分信息: http : //prntscr.com/me51e0
好的我明白了
您当前正在从js而不是<id>
发送room-<id>
,这就是您的函数返回空值的原因。 您可以在hotelRooms()
使用以下内容
$postID = explode("room-",$_POST['post_id'])[1];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.