我正在尝试向
functions.php
文件发出获取请求。我试图避免使用 jQuery 和 Ajax,这就是我使用标准 fetch API 的原因。
我的主题页面之一中的代码:
<button @click="load()">test</button>
脚本部分位于同一文件中:
<script>
function load() {
fetch('<?php echo admin_url('admin-post.php'); ?>', {
method: 'POST',
headers: {
'x-requested-with': 'XMLHttpRequest'
},
body: JSON.stringify({
action: 'my-action'
})
}).then(data => {
console.log(data);
})
}
</script>
我的
functions.php
文件中的代码:
add_action('wp_ajax_my_action' , 'data_fetch');
add_action('wp_ajax_nopriv_my_action','data_fetch');
function data_fetch(){
echo "hi";
}
在控制台中,响应有效,但没有返回任何内容。我认为它只是找到文件,因此返回 200,但
data_fetch
函数从未执行。
我怎样才能让它发挥作用?
感谢您的帮助;)。
我关注了这篇文章:https://www.it-swarm.dev/de/functions/ajax-live-suche-nach-posttitel/961942434/
我认为您不需要为该示例使用特定的标头请求
另外,尝试使用
FormData()
:
"use strict";
(function () {
var data = new FormData(); // create an Object and take your data
data.append("action", "my-action");
fetch([Object Object], { // use your ajax url instead of ***[Object Object]***
method: "POST",
credentials: "same-origin",
body: data, // put your data into fetch body
})
.then((response) => response.text())
.then((data) => {
if (data) {
console.log(data);
}
})
.catch((error) => {
console.log("[ OPS!! my_action ]");
console.error(error);
});
})();
您可以将操作添加到 url 作为参数,这对我有用
.....
fetch('<?php echo admin_url('admin-post.php') . "?action=my-action"; ?>', {
.....