0
add_action( 'wp_footer', function () { ?>
  <script type='text/javascript' id='ajax'>
    const ajaxUrl = "<?php echo admin_url('admin-ajax.php'); ?>";
    async function httpRequest(url = '', data = {}, method = 'POST') {
      const response = await fetch(url, { method: method, 
        credentials: 'same-origin',
        headers: { 
          'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
          'Cache-Control': 'no-cache',
        },
        body: new URLSearchParams(data)
      });
      return response.text();
    }

    document.querySelector('#roll-title-btn').addEventListener('click', async function() {
      const searchTerm = document.getElementById('roll-title');
      if (searchTerm.value.trim().length) {
        const result = await httpRequest(ajaxUrl,  { action: 'filter_ajax', 'roll-title': searchTerm.value });
        console.log(result);
      }
    })
  </script>
<?php } );

add_action( 'wp_ajax_nopriv_filter_ajax', 'filter_ajax' );
add_action( 'wp_ajax_filter_ajax', 'filter_ajax' );
function filter_ajax() {
  echo "TESTING";
  wp_die();
}

每当我尝试发送 HTTP 请求时,它都会抛出 400 个错误请求并打印 0 作为结果。试图实现一个过滤器插件,但上面的代码片段根本不起作用。我尝试了 StackOverflow 的多种解决方案,但都没有奏效。

4

1 回答 1

0

在这里,我将分享我今天开发的工作代码,因此您可以在此处查看。

//First I enqueue script using action in function.php file
wp_enqueue_script( 'custom-js', get_stylesheet_directory_uri().'/assets/js/custom.js', array(), '1.0.0', 'true' );
//Then I localize custom js for admin ajax
wp_localize_script( 'custom-js', 'my_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
//I choose action and javascript object "my_ajax_object"

//Now I create custom.js as per mentioned above path
$(function(){   
    $('#capture').click(function(){
    //capture is button id.
    //here is the ajax call
    var value = '123';
    jQuery.ajax({
                    type: "post",
                    dataType: "HTML",
                    url: my_ajax_object.ajax_url,
                    data : {action: "my_ajax_object","value":value},
                    success: function(msg){
                        console.log(msg);
                    }
                });

    });
});
//Now I wrote ajax function
add_action( 'wp_ajax_nopriv_my_ajax_object', 'my_ajax_object' );
add_action( 'wp_ajax_my_ajax_object', 'my_ajax_object' );

function my_ajax_object()
{
    $value = $_POST['value'];
    $response = '<p>value is '.$value.'<p>';
    return $response;

    wp_die();
}

于 2021-10-01T04:53:11.343 回答