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

PHP+Ajax数据同页展示时升序降序按钮点击失效问题咨询

问题修复方案

以下是导致排序功能失效的核心问题及对应修复代码:

核心问题梳理

  • 排序按钮为submit类型,放在form标签内点击会触发默认表单提交,导致页面刷新,ajax请求无法正常执行
  • 升序按钮没有设置id="ascd",ascdRecord函数内错误嵌套了一层点击事件绑定,且ajax请求未传递ascd参数,后端无法触发升序查询逻辑
  • 缺少降序对应的前端函数及后端处理逻辑
  • 插入数据代码未从POST请求中读取参数,且存在SQL注入风险

1. add.php 排序按钮部分修改

将排序按钮的类型改为button,避免默认提交行为,补充id属性,移除不需要的form包裹:

<section align="center"> 
    <button type="button" class="btn btn-success" id="ascd" onclick="ascdRecord();">Ascending</button>
    <button type="button" class="btn btn-success" id="desc" onclick="descRecord();">Descending</button>
</section>

2. JavaScript 函数修改

删除ascdRecord内多余的事件绑定,补充请求参数,新增descRecord函数:

// 升序函数重写
function ascdRecord()
{
    $.ajax({
        url: "data.php",
        type: "POST",
        data: {ascd: 1},
        dataType: "html",
        success: function(data)
        {
            $('#records').html(data);
        }
    });
}
// 新增降序函数
function descRecord()
{
    $.ajax({
        url: "data.php",
        type: "POST",
        data: {desc: 1},
        dataType: "html",
        success: function(data)
        {
            $('#records').html(data);
        }
    });
}

3. data.php 代码修改

补充降序查询逻辑,修复插入数据的参数读取问题,添加SQL注入防护:

// 新增降序处理逻辑
if(isset($_POST['desc']))
{
    echo "<div class='result'>";
    $data = '<table>
    <tr>
    <th>Title</th>
    <th>Description</th>
    </tr>
    ';
    $fetch_query = "select * from app.add order by title desc";
    $fetch_run = mysqli_query($con, $fetch_query);
    if(mysqli_num_rows($fetch_run) > 0)
    {
        while($row = mysqli_fetch_array($fetch_run))
        {
            $data .= '<tr style="border: 1px solid black; padding: 8px; text-align: center">
            <td style="border: 1px solid black; padding: 8px; text-align: center">'.$row['title'].'</td>
            <td style="border: 1px solid black; padding: 8px; text-align: center">'.$row['description'].'</td>
            <td>
            <button onclick="DeleteUser('.$row['id'].')">Delete</button>
            </td>
            </tr>';
        }
    }
    $data .= '</table>';
    echo $data;
    echo "</div>";
}

// 修复插入数据逻辑
if(isset($_POST['title']) && isset($_POST['description']))
{
    // 转义参数避免SQL注入
    $title = mysqli_real_escape_string($con, $_POST['title']);
    $description = mysqli_real_escape_string($con, $_POST['description']);
    $insert_query = "insert into app.add (title, description) values('$title','$description')";
    $query_run = mysqli_query($con, $insert_query);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 09:00:04