php wp-ajax工作正常,但wp_ajax_nopriv不工作

kqlmhetl  于 2022-12-02  发布在  PHP
关注(0)|答案(2)|浏览(175)

我正在尝试为一个博客创建一个搜索栏,如果我登录的话,这个搜索栏可以正常工作,但是当我没有注销的时候就不行了。作为注销的用户,它返回一个空数组,成功代码为200。如果有人能帮助我,我将非常感激
下面是我PHP文件
`

function get_ajax_posts() {
    $posts_d =array();
    // Query Arguments
    $args = array(
        'post_type' => 'custom_posts',
        'post_status' => 'publish',
        'posts_per_page' => -1,
        'order' => 'DESC',
        'orderby' => 'date',
    );

    // The Query
    $ajaxposts = new WP_Query($args); // changed to get_posts from wp_query, because `get_posts` returns an array
    if($ajaxposts->have_posts(  )){
        while($ajaxposts->have_posts(  )){
            $ajaxposts->the_post();
            array_push($posts_d, array(
                'title' => get_the_title(),
                'url'   => get_permalink()
            ));
        }
    }
    echo json_encode( $posts_d );

    exit; // exit ajax call(or it will return useless information to the response)
}

// Fire AJAX action for both logged in and non-logged in users
// add_action('wp_ajax_nopriv_get_ajax_posts', 'get_ajax_posts');
add_action('wp_ajax_get_ajax_posts', 'get_ajax_posts');
add_action('wp_ajax_nopriv_get_ajax_posts', 'get_ajax_posts');

wp_localize_script( 'hello-elementor-child-js', 'script',
            array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );

下面是我的javascript代码

jQuery('#s').on('keyup',function(){
  $ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>"
    jQuery.ajax({
      type: 'POST',
      dataType: "json", // add data type
      // url: script.ajax_url,
      url: $ajaxurl,
      data: { action : 'get_ajax_posts' },
      success: function( response ) {
          var jobs = '';
          var count = 0;
          var text = jQuery('#s').val().toLowerCase();
          if (!arr || arr.length === 0){
            var arr = jQuery(response.filter(function(value){
              text = text || null;
              return value.title.toLowerCase().includes(text);
            }))
          };
          jQuery.each( arr, function( key, value ) {
            if (count == 5){
              return false;
            } else {
              jobs += '<a href="' + value.url + '"><p>' + value.title + '</p></a>';
              count++;
            }
            } );
            jQuery('#livesearch').html(jobs);
      }
    });
    });

`

lf5gs5x2

lf5gs5x21#

要从主题文件发送 AJAX 请求,我们可以使用wp_localize_script全局声明我们的javascript变量。

您需要本地化脚本。

add_action( 'init', 'load_files' );
function load_files() {
    wp_enqueue_script( 'custom-js', PATH_OF_YOUR_FILE , array( 'jquery' ), '1.0.0', true );
    wp_localize_script( 'custom-js', 'myVar', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}

在js文件中

jQuery("#s").on("keyup", function () {
  let url = myVar.ajax_url; //pass your localize variable for ajax url
  jQuery.ajax({
    type: "POST",
    dataType: "json", // add data type
    url: url,
    data: { action: "get_ajax_posts" },
    success: function (response) {
      var jobs = "";
      var count = 0;
      var text = jQuery("#s").val().toLowerCase();
      if (!arr || arr.length === 0) {
        var arr = jQuery(
          response.filter(function (value) {
            text = text || null;
            return value.title.toLowerCase().includes(text);
          })
        );
      }
      jQuery.each(arr, function (key, value) {
        if (count == 5) {
          return false;
        } else {
          jobs += '<a href="' + value.url + '"><p>' + value.title + "</p></a>";
          count++;
        }
      });
      jQuery("#livesearch").html(jobs);
    },
  });
});

检查并让我知道 AJAX 调用是否工作。

lc8prwob

lc8prwob2#

PHP code

function get_ajax_posts() {
    $posts_d =array();
    // Query Arguments
    $args = array(
        'post_type' => 'post', //change post_type with your custom post type
        'post_status' => 'publish',
        'posts_per_page' => -1,
        'order' => 'DESC',
        'orderby' => 'date',
    );

    // The Query
    $ajaxposts = new WP_Query($args); // changed to get_posts from wp_query, because `get_posts` returns an array
    if($ajaxposts->have_posts(  )){
        while($ajaxposts->have_posts(  )){
            $ajaxposts->the_post();
            array_push($posts_d, array(
                'title' => get_the_title(),
                'url'   => get_permalink()
            ));
        }
    }
    echo json_encode( $posts_d );

    exit; // exit ajax call(or it will return useless information to the response)
}

// Fire AJAX action for both logged in and non-logged in users
// add_action('wp_ajax_nopriv_get_ajax_posts', 'get_ajax_posts');
add_action('wp_ajax_get_ajax_posts', 'get_ajax_posts');
add_action('wp_ajax_nopriv_get_ajax_posts', 'get_ajax_posts');

add_action( 'wp_enqueue_scripts',  'custom_localize_script' );
function custom_localize_script(){
    wp_localize_script( 'hello-elementor-child-js', 'ajax_object', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}

Javascript code

<script type="text/javascript">
            jQuery('#s').on('keyup',function(){
                jQuery.ajax({
                    type: 'POST',
                    dataType: "json", // add data type
                    url: ajax_object.ajaxurl,
                    data: { action : 'get_ajax_posts' },
                    success: function( response ) {
                        console.log(response);
                        var jobs = '';
                        var count = 0;
                        var text = jQuery('#s').val().toLowerCase();
                        if (!arr || arr.length === 0){
                            var arr = jQuery(response.filter(function(value){
                                text = text || null;
                                return value.title.toLowerCase().includes(text);
                            }))
                        };
                        jQuery.each( arr, function( key, value ) {
                            if (count == 5){
                                return false;
                            } else {
                                jobs += '<a href="' + value.url + '"><p>' + value.title + '</p></a>';
                                count++;
                            }
                        });
                        jQuery('#livesearch').html(jobs);
                    }
                });
            });
        </script>

我也分享了我的工作代码附件。请检查,让我知道,如果你发现任何问题

相关问题