首页 > 解决方案 > 数据变量返回为 [object Object]

问题描述

我有一个带有数据的按钮:

data-boutique-id="<?php echo esc_attr(get_the_ID());

在我的 main.js 中,我有 2 个使用这 2 个变量的 jQuery 函数:

$fav = $('.fav-btn'),
boutiqueId = $fav.data('boutique-id');

我的on('click')函数工作正常,它确实返回了data-boutique-id. 但是我的ready()函数不起作用,变量boutiqueId正在返回[object Object]而不是 Id。一定有什么我不知道的。

var $fav = $('.fav-btn'),
  boutiqueId = $fav.data('boutique-id');

$fav.ready(function(theBoutique) {     
  $.ajax({
    type: 'GET',
    data: {
      action: 'check-fav',
      boutiqueId: theBoutique
    },
    url: '/wp-json/fav_ajax/v1/manage_fav/'
  }).done(function(_data) { 
    console.log(_data);
  });
});
function manage_fav_rest_route() 
{
  // Path to ajax 
  register_rest_route(
    'fav_ajax/v1',
    '/manage_fav/',
    array(
      'methods' => WP_REST_SERVER::READABLE,
      'callback' => 'handle_rest_call'
    )
  );
}

function handle_rest_call() 
{
  $the_boutique = $_GET['boutiqueId'];
  $the_action =  $_GET['action'];

  if ('check-fav' == $the_action) 
  {
    return $the_boutique;
  }
}

标签: phpjquery

解决方案


我必须用里面的函数创建一个事件。

$fav.ready(function( event ) {
    console.log( "event ready!" );

  // Validate user is logged in
  if( isLoggedIn) {
    checkFav( boutiqueId );
  }
  });

  function checkFav( theBoutique ) {
    console.log( "function ready!" );

        $.ajax({
        type: 'GET',
        data: {
          action : 'check-fav',
          boutiqueId : theBoutique
        },
       url: '/wp-json/fav_ajax/v1/manage_fav/'

推荐阅读