You need to enable JavaScript to run this app. 使用navigator.sendBeacon调用WordPress AJAX接口返回400错误如何解决
优惠活动
大模型
产品
解决方案
定价
更多

使用navigator.sendBeacon调用WordPress AJAX接口返回400错误如何解决

问题原因分析
  • 核心原因是navigator.sendBeacon的传参格式不符合PHP解析规则:直接传入普通JS对象作为第二个参数时,浏览器会自动将对象转为[object Object]的纯文本,请求头Content-Type会被设为text/plain,PHP无法解析出$_POST数组,导致WordPress的admin-ajax.php无法读取到必填的action参数,直接返回400错误。
修复方案

1. 调整JS代码,用FormData封装参数

let array_data_on_unload = [url1, url2, url3]; //array of urls
if(array_data_on_unload.length >= 1){
    // 用FormData封装参数,确保PHP可以正常解析到$_POST
    let formData = new FormData();
    formData.append('action', 'delete_on_unload');
    formData.append('source_urls', JSON.stringify(array_data_on_unload));
    let result = navigator.sendBeacon(window.location.protocol+'//'+window.location.hostname+'/wp-admin/admin-ajax.php', formData);
    console.log(result);
}

2. 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' => false);
    // 先判断参数是否存在,避免异常报错
    if(isset($_POST['source_urls'])){
        $file_urls = json_decode(stripslashes($_POST['source_urls']));
        if(is_array($file_urls)){
            foreach($file_urls as $file_url){
              //do the delete operation
            }
            $response['success'] = true;
        }
    }
    exit(json_encode($response));
}
补充说明
  • 如果你的站点启用了CSRF校验(比如部分安全插件、自定义主题加了nonce校验),需要在FormData里额外追加对应的nonce参数,否则也可能触发400错误。
  • navigator.sendBeacon返回true仅代表浏览器成功将请求加入发送队列,不代表请求本身的参数和返回正常,这一点和普通AJAX的回调逻辑不同。

内容的提问来源于stack exchange,提问作者toddash

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 16:21:03