【问题标题】:Select2 Ajax not Calling wp_ajax_ in Wordpress (Javascript error, not a WP error)Select2 Ajax 未在 Wordpress 中调用 wp_ajax_(Javascript 错误,不是 WP 错误)
【发布时间】:2016-01-22 19:53:51
【问题描述】:

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

这是我的functions.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 会访问数据函数和“返回”,但永远不会调用操作(或者至少该函数的 PHP 永远不会运行)。关于如何找出问题所在有什么建议吗?我相信这是一个 javascript 错误而不是 Wordpress 错误,这就是为什么我在 stackoverflow 中有它,但如果我错了,请纠正我。

【问题讨论】:

  • 你的JS控制台有错误吗?该请求是否会在您的网络选项卡中生成任何错误?是否曾经生成过请求?
  • 不,我在控制台或网络选项卡中找不到任何由此产生的错误。

标签: ajax wordpress select jquery-select2 jquery-select2-4


【解决方案1】:

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

【讨论】:

  • 谢谢我曾经有过,但改变了它。我在上面更正了它,但函数永远不会到达那个点,因为在数据函数发生之前出现了问题。
猜你喜欢
  • 2014-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-29
  • 1970-01-01
  • 1970-01-01
  • 2012-12-09
  • 1970-01-01
相关资源
最近更新 更多