webservice返回bool,使用ajax

时间:2010-02-05 09:43:55

标签: asp.net javascript jquery web-services asp.net-ajax

我得到了一个密码验证的jQuery提示符。我使用ajax webservice来完成这项任务。现在我的困惑是我应该如何处理ajax调用并使函数bool?

我在2小时前开始使用ajax和webservices,所以很好。

        $(document).ready(function() {
    $("#sayHelloButton").click(function() {
            jPrompt('Password:', 'Password', 'Password', function(r) {
                if (CheckPassword(r) == true) window.location = "http://www.asp.net";
                else alert('Wrong password');
            });
        });
    });


function CheckPassword(psw) {
        $.ajax({
            type: "POST",
            url: "dummywebservice.asmx/CheckPassword",
            data: "{'" + $('#name').val() + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json"              
        });
    }

web服务

[WebMethod]
    public bool CheckPassword(string password)
    {
        if(!string.IsNullOrEmpty(password))
        {
            if (password == "testpassword")
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        else
        {
            return false;
        }            
    }

1 个答案:

答案 0 :(得分:0)

更改CheckPassword函数以执行如下所示的true和false回调:

function CheckPassword(psw, ifTrue, ifFalse) {
   $.ajax({
      type: "POST",
      url: "dummywebservice.asmx/CheckPassword",
      data: "{'" + $('#name').val() + "'}",
      contentType: "application/json; charset=utf-8",
      dataType: "json",
      success: function(data, textStatus, XMLHttpRequest) {
          if (data)
             ifTrue();
          else
             ifFalse();
      }
   });
}

然后像这样调用函数:

$(document).ready(function() {
   $("#sayHelloButton").click(function() {
   jPrompt('Password:', 'Password', 'Password', function(r) {
      CheckPassword(r, 
         function ifTrue() {
            window.location = "http://www.asp.net";
         },
         function ifFalse() {
            alert('Wrong password');
         }
      );
   });