c# - 为什么我的 Ajax 不工作?

标签 c# javascript jquery ajax

我试图从 Ajax 代码调用方法,但我的 ajax 代码根本无法进入该方法。 我的代码可能有什么问题?

C# 方法:

[WebMethod]
public static bool UserNameExists(string sendData)
{
    bool a;

    a = DataCheck.CheckDBUser(sendData);

    return a;
}

Ajax :

$('#Button2').click(function () {
    var name = document.getElementById('<%= UserTxt.ClientID %>').value;
    $.ajax({
        type: 'POST',
        url: 'Register.aspx/UserNameExists',
        data: '{ }',
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function(msg) {
            if (msg.d == true) {
                $("#UserLb").text("User Name is OK!");
            } else {
                $("#UserLb").text("User Name NOT avliable!");
            }
        }
    });
});

注意:当我使用 alert();命令只是为了检查它是否正在运行 - 没问题。

谢谢。

最佳答案

您的方法需要一个您没有在 ajax 调用中传递的参数。 这样做:

$('#Button2').click(function () {
    var name = document.getElementById('<%= UserTxt.ClientID %>').value;

    $.ajax({
        type: 'POST',
        url: 'Register.aspx/UserNameExists',
        data: {sendData:name },
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function(msg) {
            if (msg.d == true) {

                $("#UserLb").text("User Name is OK!");
            } else {
                $("#UserLb").text("User Name NOT avliable!");
            }

        }
    });
});

并从 data:'{}' 中删除单引号,它应该是 data: {}

关于c# - 为什么我的 Ajax 不工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22882299/

相关文章:

c# - 在 C# 中比较二进制文件

javascript - 如何向 Klout API 发送批量请求

javascript - 如何在 WordPress 管理控制面板中运行 Javascript?

jQuery - 将 div 包裹到特定元素

c# - 向 Windows 服务发送 Windows 消息

c# - 使用 OctoKit 获取存储库的所有文件

c# - 在 HTML5 Canvas /页面中直播音频?

javascript - AngularJS 单元测试 - 未定义不是函数

javascript - 监听VueJS父组件中的事件调用方法

javascript - 如何将 if 语句添加到对象 block