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

如何在PHP中实现分类名不可用时禁用提交按钮

解决分类名占用时禁用提交按钮的问题

问题原因分析

  • 当前代码仅在输入为空时处理了按钮禁用状态,但AJAX返回分类已存在的提示时,没有对提交按钮的状态做修改
  • 定义了输入格式正则但未实际用于验证
  • 提交按钮初始状态未禁用,存在误提交风险
  • 原PHP代码存在SQL注入漏洞,需优化

优化方案(推荐使用JSON交互)

1. 修改后端PHP代码(返回结构化JSON)

将原cat_name_status.php改为返回JSON格式数据,便于前端准确判断状态:

<?php
require('../../dbc/dbconn.php');
include('../../includes/scripts.php');
include('../../includes/functions.php');
header('Content-Type: application/json');

$response = ['exists' => false, 'message' => ''];
if(isset($_POST['cat_name'])){
    $cat_name = clearInput($condb, $_POST['cat_name']);
    
    // 使用预处理语句避免SQL注入
    $stmt = mysqli_prepare($condb, "SELECT cat_name FROM pos_categories WHERE cat_name = ?");
    mysqli_stmt_bind_param($stmt, "s", $cat_name);
    mysqli_stmt_execute($stmt);
    mysqli_stmt_store_result($stmt);
    
    if(mysqli_stmt_num_rows($stmt) > 0){
        $response['exists'] = true;
        $response['message'] = '<p class="text-danger"><strong><i class="fas fa-times-circle"></i> Category Name already exists</strong></p>';
    } else {
        $response['message'] = '<p class="text-success"><strong><i class="fas fa-check-circle"></i> Category Name is available</strong></p>';
    }
    mysqli_stmt_close($stmt);
}

echo json_encode($response);
?>

2. 修改前端jQuery脚本

更新JS逻辑,处理输入验证、AJAX响应并控制按钮状态:

<script>
$(document).ready(function(){
    // 初始状态禁用提交按钮
    $("#create").attr("disabled", true);

    $("#category_name").keyup(function(){
        var cat_name = $(this).val().trim();
        var usernameRegex = /^[a-zA-Z0-9]+$/;

        if(cat_name === ''){
            $("#cat_name_status").html("<span style='color: red;'><i class='fas fa-times-circle'></i> Enter a valid category name</span>");
            $("#create").attr("disabled", true);
        } else if(!usernameRegex.test(cat_name)){
            $("#cat_name_status").html("<span style='color: red;'><i class='fas fa-times-circle'></i> Category name can only contain letters and numbers</span>");
            $("#create").attr("disabled", true);
        } else {
            $.ajax({
                url: 'cat_name_status.php',
                type: 'post',
                dataType: 'json',
                data: {cat_name: cat_name},
                success: function(response){               
                    $('#cat_name_status').html(response.message);
                    // 根据分类是否存在控制按钮状态
                    $("#create").attr("disabled", response.exists);
                },
                error: function(){
                    $("#cat_name_status").html("<span style='color: orange;'><i class='fas fa-exclamation-circle'></i> Unable to check availability</span>");
                    $("#create").attr("disabled", true);
                }
            });
        }
    });
});
</script>

替代方案(不修改PHP,解析HTML响应)

如果不想修改后端,可以通过解析返回的HTML内容来判断状态:

<script>
$(document).ready(function(){
    $("#create").attr("disabled", true);

    $("#category_name").keyup(function(){
        var cat_name = $(this).val().trim();
        var usernameRegex = /^[a-zA-Z0-9]+$/;

        if(cat_name === ''){
            $("#cat_name_status").html("<span style='color: red;'><i class='fas fa-times-circle'></i> Enter a valid category name</span>");
            $("#create").attr("disabled", true);
        } else if(!usernameRegex.test(cat_name)){
            $("#cat_name_status").html("<span style='color: red;'><i class='fas fa-times-circle'></i> Category name can only contain letters and numbers</span>");
            $("#create").attr("disabled", true);
        } else {
            $.ajax({
                url: 'cat_name_status.php',
                type: 'post',
                data: {cat_name: cat_name},
                success: function(response){               
                    $('#cat_name_status').html(response);
                    // 判断返回内容是否包含错误提示
                    var hasError = $('#cat_name_status').find('.text-danger').length > 0;
                    $("#create").attr("disabled", hasError);
                    
                    // 如果返回空,添加可用提示
                    if(response.trim() === '' && !hasError){
                        $('#cat_name_status').html("<span style='color: green;'><i class='fas fa-check-circle'></i> Category Name is available</span>");
                        $("#create").attr("disabled", false);
                    }
                },
                error: function(){
                    $("#cat_name_status").html("<span style='color: orange;'><i class='fas fa-exclamation-circle'></i> Unable to check availability</span>");
                    $("#create").attr("disabled", true);
                }
            });
        }
    });
});
</script>

关键改进点

  • 初始禁用提交按钮,避免无效提交
  • 加入输入格式验证(使用定义好的正则)
  • 根据AJAX返回的状态准确控制按钮禁用/启用
  • 修复后端SQL注入风险(推荐方案)
  • 添加AJAX请求失败的异常处理

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 10:14:54