Проблема с fetch и admin-ajax
-
Пытаюсь реализовать кнопку «Загрузить еще» для постов.
В интернете полно примеров с jquery, но я не исопльзую его в своем проекте.
4 часа просидел так и не понял в чем причина ошибки 400 от admin-ajax.
Судя по тому что я вычитал это то что admin-ajax не может принять в себя json как запрос, но что тогда туда передавать? + В полезной нагрузке данные почему то приходят.
Буду благодарен за любую наводку.JS:
const loadMoreBtn = document.querySelector(".load-more"); const outputContaner = document.querySelector("#live-loading"); function getNewPosts() { const data = new FormData(); data.append("action", "loadmore"); data.append("paged", ajaxparam.current_page); fetch(ajaxparam.ajaxurl, { method: "POST", body: JSON.stringify({ action: "loadmore", paged: ajaxparam.current_page, }), }) .then((response) => { response.json(); }) .then((data) => { console.log(data); }) .catch((error) => { console.error(error); }); } loadMoreBtn.addEventListener("click", getNewPosts);
function.php
function loadmore_posts() { // prepare our arguments for the query $args = json_decode(stripslashes($_POST['query']), true); $args['paged'] = $_POST['page'] + 1; // we need next page to be loaded $args['post_type'] = 'portfolio'; // it is always better to use WP_Query but not here query_posts($args); if (have_posts()) : // run the loop while (have_posts()) : the_post(); get_template_part('temp/portfolio-item'); endwhile; endif; die; // here we exit the script and even no wp_reset_query() required! } add_action('wp_ajax_loadmore', 'loadmore_posts'); // wp_ajax_{action} add_action('wp_ajax_nopriv_loadmore', 'loadmore_posts'); // wp_ajax_nopriv_{action}
Ошибка:
Failed to load resource: the server responded with a status of 400 (Bad Request)
В сеть — полезная нагрузка:
`{action: «loadmore», paged: «1»}
action
:
«loadmore»
paged
:
«1»`В ответе: 0
Заголовки:URL запроса: http://rsn.test/wp-admin/admin-ajax.php Метод запроса: POST Код статуса: 400 Bad Request Удаленный адрес: 127.0.0.1:80 Правило для URL перехода: strict-origin-when-cross-origin Access-Control-Allow-Credentials: true Access-Control-Allow-Origin: http://rsn.test Cache-Control: no-cache, must-revalidate, max-age=0 Connection: close Content-Length: 1 Content-Type: text/html; charset=UTF-8 Date: Fri, 07 Oct 2022 00:02:32 GMT Expires: Wed, 11 Jan 1984 05:00:00 GMT Server: Apache/2.4.47 (Win64) OpenSSL/1.1.1k PHP/7.4.19 X-Powered-By: PHP/7.4.19 X-Robots-Tag: noindex Accept: */* Accept-Encoding: gzip, deflate Accept-Language: ru,en;q=0.9 Cache-Control: no-cache Connection: keep-alive Content-Length: 33 Content-Type: text/plain;charset=UTF-8 Cookie: wordpress_68330295ecaef78a0dfa858ddbfc8c0f=admin%7C1666141469%7CLRdXgAPdNUxtCMP8CtV9e9FqEtpGBV9yLE5yWdttZUD%7C048dfc634fd01b0704ab0e0906287a4d145c7cbd8dab871388edefb8164f90a1; wordpress_test_cookie=WP%20Cookie%20check; wp_lang=ru_RU; wordpress_logged_in_68330295ecaef78a0dfa858ddbfc8c0f=admin%7C1666141469%7CLRdXgAPdNUxtCMP8CtV9e9FqEtpGBV9yLE5yWdttZUD%7C3294fe4bfb5430ea858e195994127c37ecc9892c38e063103fc5980973ed1e88; wp-settings-time-1=1664967419; wp-settings-1=libraryContent%3Dbrowse Host: rsn.test Origin: http://rsn.test Pragma: no-cache Referer: http://rsn.test/portfolio/ User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36
Если я меню объект с данными на формдата то у меня идет ошибка
VM2356:1 Uncaught (in promise) SyntaxError: Unexpected end of JSON input
, но при этом ошибки в admin-ajax нет
- Тема «Проблема с fetch и admin-ajax» закрыта для новых ответов.