我尝试在页面卸载/visibilityChange上使用ajax请求。我发现navigator.sendBeacon是最好的选择。我尝试在WordPress中使用它,请求正在发送,但我收到'POST 400 bad request‘错误。
下面是我的js代码:
let array_data_on_unload = [url1, url2, url3]; //array of urls
let unload_delete_data = {
action: 'delete_on_unload',
source_urls: JSON.stringify(array_data_on_unload)
};
if(array_data_on_unload.length >= 1){
let result = navigator.sendBeacon(window.location.protocol+'//'+window.location.hostname+'/wp-admin/admin-ajax.php', unload_delete_data);
console.log(result); //returns true in console
}我用functions.php编写的php代码
add_action( 'wp_ajax_delete_on_unload', 'delete_on_unload' );
add_action( 'wp_ajax_nopriv_delete_on_unload', 'delete_on_unload' );
function delete_on_unload(){
$response = array('success' => true);
$file_urls = json_decode(stripslashes($_POST['source_urls']));
foreach($file_urls as $file_url){
//do the delete operation
}
exit(json_encode($response));
}为什么这是返回POST [domain]/wp-admin/admin-ajax.php 400 (Bad Request)错误?
发布于 2021-08-20 17:08:18
我想通了。我们无法在sendBeacon中更改标头。所以为了让它以json对象的形式发送数据。我们可以将其作为formData();发送。请参见下面的代码
let unload_formData = new FormData();
unload_formData.append('action', 'delete_on_unload');
unload_formData.append('source_urls', JSON.stringify(array_data_on_unload));https://stackoverflow.com/questions/68864550
复制相似问题