【问题标题】:Why my Ajax not working?为什么我的 Ajax 不工作?
【发布时间】:2014-05-17 22:02:13
【问题描述】:

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

C#方法:

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

    a = DataCheck.CheckDBUser(sendData);

    return a;
}

阿贾克斯:

$('#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();命令只是为了检查它是否正在运行 - 没问题。

谢谢。

【问题讨论】:

    标签: c# javascript jquery ajax


    【解决方案1】:

    您需要定义一些数据以发送到函数。您也可以定义该方法应该采用这样的 HttpPost:

    [WebMethod]
    [HttpPost]
    public static bool UserNameExists(string sendData)
    {
        bool a;
    
        a = DataCheck.CheckDBUser(sendData);
    
        return a;
    }
    

    并定义一些数据发送给方法:

    $('#Button2').click(function () {
    
        var name = document.getElementById('<%= UserTxt.ClientID %>').value;
    
    
        $.ajax({
            type: 'POST',
            url: 'Register.aspx/UserNameExists',
            data: {sendData: "Hello" },
            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!");
                }
    
            }
        });
    });
    

    【讨论】:

      【解决方案2】:

      您的方法需要一个您没有在 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: {}

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-09-20
        • 2012-04-14
        • 2016-09-15
        • 2012-02-14
        • 2012-08-10
        • 2013-07-27
        相关资源
        最近更新 更多