无法在ajax调用中测试Web Service的返回值

时间:2012-10-12 20:11:05

标签: asp.net ajax web-services

我有以下jQuery代码:

var isUsernameAvailable = false;

function CheckUsername(uname) {
        $.ajax({
            method: "POST",
            url: "IsUsernameAvailable.asmx/IsAvailable",
            data: { username: uname },
            dataType: "text",
            success: OnSuccess,
            error: OnError
        });     // end ajax
    }   // end CheckUsername
    function OnSuccess(data) {            
        if (data == true) {    // WHY CAN'T I TEST THE VALUE
            isUsernameAvailable = true;
        } else {
            isUsernameAvailable = false;
            $('#error').append('Username not available');
        }
    }
    function OnError(data) {
        $('#error').text(data.status + " -- " + data.statusText);            
    }

一个简单的Web服务:

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following     line. 
[System.Web.Script.Services.ScriptService]
public class IsUsernameAvailable : System.Web.Services.WebService {

    public IsUsernameAvailable () {

        //Uncomment the following line if using designed components 
        //InitializeComponent(); 
    }

    [WebMethod]
    public bool IsAvailable(string username) {
        return (username == "xxx");
    }

}

我无法从我的网络服务中读取返回值。当我在回调函数(data参数)中打印出值时,我得到truefalse(注意前面的空格)。

当我打印data.d时,它会显示undefined。仅供参考,每次都会遇到网络服务方法。

1 个答案:

答案 0 :(得分:1)

您将dataType指定为text。这会让我相信你得到的响应实际上是一个字符串而不是一个布尔值。将dataType切换为json将为您提供Javascript对象。

编辑:parsererror的原因是因为您返回的布尔值实际上是转换为字符串的.NET布尔值。当.ToString()最终被调用以获得实际的HTTP响应时,它最终会被TrueFalse。在JSON中,布尔值为truefalse(注意大小写)。当jQuery试图解析响应时,它不认为它是一个正确的布尔值并抛出错误。

根据您使用的ASP.NET风格,您有几个选择。如果您正在使用MVC或Web API,请按以下方式返回:

return Json(username == "xxx", JsonRequestBehavior.AllowGet);

如果您没有使用这些技术,那么最好将返回类型更改为字符串,然后调用:

return new JavaScriptSerializer().Serialize(username == "xxx");

您需要导入前一个代码段的System.Web.Script.Serialization命名空间才能生效。