Select2 Ajax not Calling wp_ajax_ in Wordpress (Javascript e



我已经尝试了我能想到的一切,但我无法让 Select2 Ajax 调用 Wordpress wp_ajax 操作。

这是我的函数.php(不包括脚本的排队和本地化):

function get_list_posts() {
  $search = sanitize_text_field( $_REQUEST['list_search'] );
  $post_type = sanitize_text_field( $_REQUEST['post_type'] );
  $post_query = new WP_Query(
    array(
      'post_type' => $post_type,
      'post_status' => 'published',
      's' => $search
    )
  );
  // Bail if we don't have any results
  if ( empty( $post_query->results ) ) {
    wp_send_json_error( $_POST );
  }
  $results  = array();
  foreach ( $post_query->results as $post ) {
    $results[] = array(
      'id' => $post->ID,
      'text' => $post->title
    );
  }
  wp_send_json_success( $results );
  die();
}
add_action( 'wp_ajax_list_posts', 'get_list_posts' );
add_action( 'wp_ajax_nopriv_list_posts', 'get_list_posts' );

还有我的JavaScript:

  $('#list-search').select2({
    minimumInputLength: 3,
    ajax: {
      url: ajax_post_params.ajax_url,
      dataType: 'json',
      data: function (term, page) {
        post_type = $(this).attr("data-post-type");
        return {
          action: 'list_posts',
          list_search: term,
          post_type: post_type
        };
      },
      processResults: function (data, params) {
        console.log(data);
        console.log(params);
        params.page = params.page || 1;
        return {
          results: data.items,
          pagination: {
            more: (params.page * 30) < data.total_count
          }
        };
      },
      cache: true
    }
  });

在调试时,ajax 会得到数据函数和"return",但永远不会调用操作(或者至少该函数的 PHP 永远不会运行)。关于我如何找出这有什么问题的任何建议?我相信这是一个javascript错误而不是Wordpress错误,这就是为什么我在stackoverflow中使用它,但是如果我错了,请纠正我。

与示例 https://select2.github.io/examples.html#data-ajax 一样,您需要在processResults函数中返回结果。