无法使用POST方法将数据从API发送到AJAX

时间:2019-01-30 09:08:41

标签: php jquery ajax post

我有一个很奇怪的问题。我的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

1 个答案:

答案 0 :(得分:0)

好吧,我明白了

您当前正在从js发送room-<id>而不是<id>,这就是为什么您的函数返回空值的原因。 您可以在hotelRooms()

中使用类似以下的内容
$postID = explode("room-",$_POST['post_id'])[1];