簡體   English   中英

無法使用POST方法將數據從API發送到AJAX

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM