我正试图在我的网站上实现过滤系统。我决定通过js来做。我创建了提取函数
let filters = document.querySelectorAll('.filters-item');
let pageUrl = wp.page_url;
const postsContainer = document.querySelectorAll('.column.is-half.is-offset-1');
filters.forEach( (item) => {
item.addEventListener('change', (e) =>{
let url = pageUrl + '/wp-admin/admin-ajax.php';
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'text/html; charset=UTF-8',
},
body: JSON.stringify({
'test': "sampledatatest",
})
}).then( function (response) {
if(response.ok) {
return response.json();
}
return Promise.reject(response);
}).then(function (data) {
console.log(data);
}).catch(function (error) {
console.warn('Error', error);
});
});
});
在我的functions.php文件中,我有一个简单的函数
add_action('wp_ajax_myfilter', 'misha_filter_function'); // wp_ajax_{ACTION HERE}
add_action('wp_ajax_nopriv_myfilter', 'misha_filter_function');
function misha_filter_function(){
$t = $_POST['test'];
echo $t;
die();
}
当我单击filter
项时,我的开发控制台中出现了错误400。我遗漏了什么?像我一样以表格的形式传递数据是正确的吗?我不想使用jQuery。
发布于 2021-01-25 01:54:32
像我一样以表格的形式传递数据是正确的吗?
如果您是指(您的body
调用的)部分,那么是的,没关系。
然而,
action
的查询,作为请求的一部分(例如通过example.com/wp-admin/admin-ajax.php?action=test
之类的URL ),以便WordPress知道它是什么AJAX操作,然后对该特定操作执行回调(S)。有关更多信息,请参见这里,但在您的示例中,AJAX操作与wp_ajax_myfilter
中的AJAX操作相同,回调是misha_filter_function()
。Content-Type
头与请求体不匹配,您应该使用application/json
而不是text/html
。但是,即使有了正确的请求主体和标题,admin-ajax.php
实际上也不支持JSON请求,因此如果您想发送JSON请求,那么您应该使用WordPress REST,并且您可能希望使用添加一个自定义端点,如my-plugin/v1/myfilter
。
否则,如果您更喜欢使用admin-ajax.php
,那么可以使用FormData()
JavaScript中的API正确地构建要发送给admin-ajax.php
的表单数据:
var formData = new FormData();
formData.append( 'action', 'myfilter' );
formData.append( 'test', 'foo bar baz' );
fetch( url, {
method: 'POST',
body: formData,
} ) // wrapped
.then( res => res.text() )
.then( data => console.log( data ) )
.catch( err => console.log( err ) );
发布于 2022-12-25 23:00:05
我认为下面是通过javascript启动ajax请求的最方便的方法。在不使用WordPress的情况下创建jQuery ajax请求。
// PHP WP ajax hook
add_action('wp_ajax_ajaxCallback', 'ajaxCallback');
// Creating data
let requestData = {
action: "ajaxCallback",
myData: "Your data",
nonce: 'test nonce'
};
// Initiating AJAX request
fetch('http://example.com/wp-admin/admin-ajax.php', {
method:"post",
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams(requestData).toString(),
}).then(function(response) {
// return response.json(); // if responce is in json.
return response.text();
}).then(function(response) {
console.log(response);
});
https://wordpress.stackexchange.com/questions/382129
复制相似问题