Wordpress使用fetch在ajax请求时返回400



已经浏览了几十个关于同一问题的主题,但没有找到任何真正有效的解决方案。

JS:

/*let data = {
test_string: 'SENDED DATA',
action: 'test_ajax_func'
}*/  // already tried
let data = new FormData();
data.append('action', 'test_ajax_func');
data.append('test_string', 'SENDED DATA');
//let data_usp = new URLSearchParams(data);  // already tried too, both with the object and FormData object
fetch(wp_localize_data.ajax_url, {
method: 'POST',
body: data,  // JSON.stringify(data) already tried, no differecne at all
headers: {
'Content-Type': 'application/json',
'Cache-Control': 'no-cache',
}
}).then(responce => {
if(responce.ok) {
console.log('ajax_request: YEP');
responce.json().then(data => console.log(data.result));
}
else {
console.log('ajax_request: NOPE');
}
}).catch(error => console.log('ERROR: ' + error));

PHP:

add_action('wp_enqueue_scripts', 'theme_styles_and_scripts');
function theme_styles_and_scripts() {
wp_register_script('ajax-test', get_template_directory_uri() . '/js/ajax-test.js', []);
wp_localize_script('ajax-test', 'wp_localize_data', ['ajax_url' => admin_url('admin-ajax.php')]);
wp_enqueue_script('ajax-test');
}
add_action('wp_ajax_test_ajax_func', 'test_ajax_func');
add_action('wp_ajax_nopriv_test_ajax_func', 'test_ajax_func');
function test_ajax_func() {
$test_string = $_POST['test_string'];
$returned_string = 'RETURNS '. $test_string;

echo json_encode(['result' => $returned_string]);
die;
}

看起来一切都应该很好,但它不断返回400坏请求。

但是如果我改变

fetch(wp_localize_data.ajax_url, {

fetch(wp_localize_data.ajax_url + '?action=test_ajax_func', {

请求开始工作,但PHP函数并没有看到$_POST['testrongtring'],只返回'returns'字符串。

所以,一些真正有效的解决方案,以正确使用获取API与WordPress甚至存在?因为我开始觉得最好完全忘记它,一直使用jQuery-ajax((。

凭据添加到代码

fetch(wp_localize_data.ajax_url, {
method: 'POST',
credentials: 'same-origin',
.
.
.

最新更新