简体   繁体   English

没有 jQuery 的 WordPress AJAX 实时搜索

[英]WordPress AJAX live search without jQuery

I'm trying to make ajax live search on WP website without usage of jQuery cause I don't want to load additional 80kb for this feature.我试图在不使用 jQuery 的情况下在 WP 网站上进行 ajax 实时搜索,因为我不想为此功能加载额外的 80kb。 I already made it work with jQuery, but when I try to rewrite script to work with Vanilla jS, I always got the issue我已经使它与 jQuery 一起工作,但是当我尝试重写脚本以与 Vanilla jS 一起工作时,我总是遇到问题

wp-admin/admin-ajax.php 400 (Bad Request) wp-admin/admin-ajax.php 400(错误请求)

working code工作代码

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 that doesn't work无效的 VANILLA JS 代码

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);

The obvious problem I see without knowing your problem is that request.send(data);我在不知道您的问题的情况下看到的明显问题是request.send(data); does not equal to { action: 'data_fetch', keyword: jQuery('#keyword').val() } instead you should be writing something like this request.send('action=data_fetch&keyword='+data);不等于{ action: 'data_fetch', keyword: jQuery('#keyword').val() }而是你应该写这样的东西request.send('action=data_fetch&keyword='+data);

Also, depending on the data value you are passing you may need to encode it.此外,根据您传递的数据值,您可能需要对其进行编码。 Again, it is somewhat hard to help you without knowing exactly the problem you are having.同样,在不确切知道您遇到的问题的情况下很难帮助您。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM