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

ASP.NET动态生成表格后AJAX返回True无提示问题排查

问题分析与解决

1. 直接语法错误

你的AJAX success回调里存在双重if嵌套的语法错误:

// 错误写法
if ( if (response.d)) { ... }

这种错误会导致浏览器无法正确解析代码,当response.d为true时,这段逻辑根本无法执行。修正为:

if (response.d) {
    alert("The user was succefully moved");
} else {
    alert("Some problem occurred");
}

2. 阻止ASP.NET按钮的默认回发行为

asp:Button默认会触发服务器端页面回发,这会导致AJAX请求还没完成,页面就已刷新,alert提示可能被覆盖或根本不显示。需要在OnClientClick中阻止默认行为:

<asp:Button ID="Button2" OnClientClick="retrieveTableValues(event); return false;" 
            onclick="Button2_Click" CssClass="btn btn-primary" runat="server" 
            Height="31px" Width="92px" Text="Move User"/>

或者在retrieveTableValues函数内部调用event.preventDefault():

function retrieveTableValues(event) {
    event.preventDefault(); // 阻止默认回发
    // 你的AJAX代码...
}

3. 验证后台WebMethod的正确性

确保后台的MoveUser方法符合ASP.NET AJAX的要求:

  • 标记[WebMethod]特性
  • 必须是public static方法
  • 返回类型为bool(或可序列化的对应类型)

示例后台代码:

using System.Web.Services;

public partial class MoveUsersWebForm : System.Web.UI.Page
{
    [WebMethod]
    public static bool MoveUser(string userToMove, string ouToMove, string userCurrentOU)
    {
        // 业务逻辑处理,返回true或false
        try
        {
            // 执行移动用户操作
            return true;
        }
        catch
        {
            return false;
        }
    }
}

4. 添加AJAX错误回调排查问题

添加error回调可以帮你排查AJAX请求是否成功发送、服务器是否返回异常:

$.ajax({
    type: "POST",
    url: "MoveUsersWebForm.aspx/MoveUser",
    data: JSON.stringify({ 'userToMove': rowValues, 'ouToMove': selectedDropDownListItem, 'userCurrentOU': userCurrentOU}),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (response) {
        if (response.d) {
            alert("The user was succefully moved");
        } else {
            alert("Some problem occurred");
        }
    },
    error: function(xhr, status, error) {
        console.error("AJAX请求失败: ", error);
        alert("请求出错,请查看控制台日志");
    }
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 17:03:09