0

我正在尝试在页面卸载/可见性更改上使用 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)错误?

4

1 回答 1

0

我想通了。我们无法更改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));
于 2021-08-20T17:08:17.673 回答