简体   繁体   English

如何将 jQuery ajax 转换为获取?

[英]How can I convert jQuery ajax to fetch?

This was my jQuery code before.这是我之前的 jQuery 代码。 Now I want to change it to fetch.现在我想将其更改为获取。

    function fetch(){
    jQuery.ajax({
        url: '<?php echo admin_url('admin-ajax.php'); ?>',
        type: 'post',
        data: { action: 'data_fetch', keyword: jQuery('#keyword').val(), pcat: jQuery('#cat').val() },
        success: function(data) {
            jQuery('#datafetch').html( data );
        }
    });
}

I have changed the code to this now but I am getting bad request 400 status code我现在已将代码更改为此,但我收到错误的请求 400 状态代码

document.querySelector('#keyword').addEventListener('keyup',()=>{
    let data = {
    action: 'data_fetch',
    keyword: document.querySelector("#keyword").value
};
let url = "<?php echo admin_url('admin-ajax.php'); ?>";
fetch(url, {
        method: 'POST', // or 'PUT'
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(data),
    })
    .then((response) => response.text())
    .then((data) => {
        document.querySelector("#datafetch").innerHTML = data;
    })
    .catch((error) => {
        console.error('Error:', error);
    });
})

Am I missing something?我错过了什么吗? It is from WordPress if this helps somehow.如果这有帮助,它来自 WordPress。

  1. You forgot the pcat property in the data object您忘记了数据 object 中的 pcat 属性
  2. jQuery, by default, sends form encoded data, not JSON encoded data. jQuery 默认发送表单编码数据,而不是 JSON 编码数据。 Use a URLSearchParams object instead of a string of JSON and omit the content-type header (the browser will add the correct one for you).使用URLSearchParams object代替字符串 JSON 并省略内容类型 header (浏览器将为您添加正确的内容类型)。

In your jQuery code you defined data as在您的 jQuery 代码中,您将data定义为

data: { action: 'data_fetch', keyword: jQuery('#keyword').val(), pcat: jQuery('#cat').val() },

and in fetch you defined it as在 fetch 中,您将其定义为

let data = {
    action: 'data_fetch',
    keyword: document.querySelector("#keyword").value
};

so, you are not passing some value which was previously passed.所以,你没有传递一些以前传递的值。 No wonder that your server errors out.难怪你的服务器出错了。 Let's change your code to让我们将您的代码更改为

let data = {
    action: 'data_fetch',
    keyword: document.querySelector("#keyword").value,
    pcat: document.getElementById("cat").value
};

and try this out.试试这个。 If it still works, then you will need to find out what differs in the request and make sure that the request you are sending via fetch is equivalent to the request you formally sent via jQuery, then it should work well, assuming that the client-side worked previously with jQuery and the server-side properly handled the requests.如果它仍然有效,那么您需要找出请求中的不同之处,并确保您通过 fetch 发送的请求等同于您通过 jQuery 正式发送的请求,那么它应该可以正常工作,假设客户端 - side 之前使用 jQuery 并且服务器端正确处理了请求。

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

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