我正在尝试在不使用jQuery的情况下在WP网站上进行ajax实时搜索,因为我不想为此功能加载额外的80kb。我已经使用jQuery,但当我尝试重写脚本以使用Vanilla jS时,我总是遇到问题
wp-admin / admin-ajax.php 400(错误请求)
工作代码
jQuery.ajax({
url: '<?php echo admin_url('admin-ajax.php'); ?>',
type: 'post',
data: { action: 'data_fetch', keyword: jQuery('#keyword').val() },
success: function(data) {
jQuery('#datafetch').html( data );
}
});
VANILLA JS CODE不起作用
var request = new XMLHttpRequest();
request.open('POST', '<?php echo admin_url("admin-ajax.php"); ?>', true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.onload = function () {
if (this.status >= 200 && this.status < 400) {
console.log('if');
} else {
console.log('else');
}
};
request.onerror = function() {
console.log('onerror');
};
var data = document.getElementById('keyword').value;
request.send(data);
我不知道你的问题看到的明显问题是request.send(data);
不等于{ action: 'data_fetch', keyword: jQuery('#keyword').val() }
而你应该写这样的东西request.send('action=data_fetch&keyword='+data);
此外,根据您传递的数据值,您可能需要对其进行编码。同样,在不确切知道您遇到的问题的情况下帮助您有点困难。