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 的多种解决方案,但都没有奏效。