You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WordPress中AJAX保存数据库异常:提交后跳转至空白admin-ajax.php

问题解决:WordPress活动评论提交后跳转至admin-ajax.php空白页

核心问题定位

你的代码存在选择器不匹配的关键错误,这是导致表单默认跳转的根本原因:

  • 表单ID为comment_form,但jQuery中绑定的是#commentform(缺失下划线),导致阻止默认提交的逻辑完全未触发,表单仍走原生提交流程跳转到admin-ajax.php。

修复后的完整代码

1. 表单代码(可保留原action,建议后续优化)

<form action="<?php echo site_url() ?>/wp-admin/admin-ajax.php" method="POST" id="comment_form">
    <textarea name="comment" id="comment" class="commentbox" rows="5" cols="120" required></textarea><br />
    <input type="hidden" name="eventid" id="eventid" value="<?php echo $id; ?>" />
    <input type="hidden" name="userid" id="userid" value="<?php echo $userid; ?>" />
    <input type="hidden" name="action" value="commentform">
    <!-- 新增CSRF验证,提升安全性 -->
    <?php wp_nonce_field('comment_form_nonce'); ?>
    <button class="commentbtn">Add Comment</button>
</form>
<div id="response"></div> 

2. 修复后的jQuery代码

修正选择器并优化事件绑定逻辑,确保阻止原生跳转:

<script>
jQuery(function($){
    // 匹配表单ID:#comment_form
    $('#comment_form').on('submit', function(e){
        // 直接阻止表单默认提交行为
        e.preventDefault();
        var $form = $(this);
        
        $.ajax({
            url: $form.attr('action'),
            data: $form.serialize(),
            type: $form.attr('method'),
            beforeSend:function(){           
                $form.find('button').text('提交中...');
            },
            success:function(res){                 
                $form.find('button').text('添加评论');
                // 根据返回结果展示提示
                if (res.success) {
                    $('#response').html('<p style="color:green;">' + res.data + '</p>');
                    // 清空评论框
                    $form.find('#comment').val('');
                } else {
                    $('#response').html('<p style="color:red;">' + res.data + '</p>');
                }
            },
            error:function(){
                $form.find('button').text('添加评论');
                $('#response').html('<p style="color:red;">提交失败,请重试</p>');
            }
        });
    });
});
</script>

3. 优化后的PHP函数

增加数据安全验证,同时返回明确的提交结果:

add_action('wp_ajax_commentform', 'comment_submit'); 
add_action('wp_ajax_nopriv_commentform', 'comment_submit'); 
function comment_submit() { 
    global $wpdb; 

    // 安全验证:校验请求合法性与字段完整性
    if (!isset($_POST['eventid'], $_POST['userid'], $_POST['comment'], $_POST['_wpnonce']) 
        || !wp_verify_nonce($_POST['_wpnonce'], 'comment_form_nonce')) {
        wp_send_json_error('非法请求');
    }

    // 清理输入数据,避免SQL注入与XSS风险
    $eventid = intval($_POST["eventid"]);
    $userid = intval($_POST["userid"]); 
    $comment = sanitize_textarea_field($_POST["comment"]);
    date_default_timezone_set("America/New_York");
    $date = date('Y-m-d H:i:s');

    $inserttable = $wpdb->prefix . "event_comments";
    $data = array(
        'eventid' => $eventid,
        'userid' => $userid,
        'content' => $comment,
        'datesaved' => $date,
    );

    $insert_result = $wpdb->insert($inserttable, $data);

    if ($insert_result) {
        wp_send_json_success('评论提交成功');
    } else {
        wp_send_json_error('保存失败,请重试');
    }
}

进阶优化建议

使用WordPress内置的wp_localize_script传递AJAX地址,避免硬编码路径:
在插件脚本注册时添加:

wp_localize_script('你的插件脚本句柄', 'ajaxObj', array(
    'ajaxUrl' => admin_url('admin-ajax.php')
));

之后jQuery中的url可改为ajaxObj.ajaxUrl,表单的action属性可直接移除。

内容的提问来源于stack exchange,提问作者Darth Mikey D

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 12:35:04