0

我正在调用页面方法,它返回此页面中的所有 HTML,而不是 1 或 0 的值。我不知道这是为什么。有人能指出我正确的方向吗?

JavaScript:

$.ajax({
    async: false,
    type: "POST",
    contentType: "application/json; charset=utf-8",
    data: '{}',
    url: "main.aspx/IsInfoComplete",
    success: function(data, textStatus, jqXHR) {
        console.log(textStatus);
        console.log(data.d);
            // act on return value:
            if(data==0) {
              // todo - 
            } else if (data==1) {
              // todo - 
            }
        }
    },
    error: function(jqXHR, textStatus, errorThrown) {
        console.log(textStatus);
    }
});

服务器:

[System.Web.Services.WebMethod()]

public int IsInfoComplete()
{
    int returnValue = 0;

using (SqlConnection conn = new SqlConnection(connString))
{
    SqlCommand cmd = conn.CreateCommand();
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.CommandText = "GetIsUserInfoComplete";
    cmd.Parameters.AddWithValue("@UserName", userName);
    conn.Open();
    try
    {
        returnValue = (int)cmd.ExecuteScalar();
    }
    catch (Exception) { /* todo - */ }
}
return returnValue;
}
4

2 回答 2

0

您可能会尝试的一件事是success像这样编写函数,

success: function (result) {
                if (result!="False") {
                    //it worked
                }
                else {
                   //it failed                 
                }
            },

并更改您的服务器端方法以返回bool. 这可能会让你得到想要的结果。我必须在我写的东西中做到这一点,它工作得很好。有点傻,你必须检查“错误”,但它有效。

注意:查找“False”一词时,大小写很重要

于 2012-09-20T15:48:54.627 回答
0

看起来这搞砸了..这里的数据是一个对象,您正试图将数据与 0 或 1 进行比较

success: function(data, textStatus, jqXHR) {
              console.log(data); // Check the format of data in object
            if(data != null){
               console.log(data.d); // Generally your actual dat is in here
              // act on return value:
              if(data.d ==0) {
               // todo - 
              } else if (data.d ==1) {
                // todo - 
            }
        }
    },

如果是这样的话,你的 WebService 首先返回一个 json 对象。你需要用这个来装饰你的 Web 服务。

[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
[System.Web.Services.WebMethod()]

public int IsInfoComplete()
{

dataType :'json'在您的 ajax 请求中设置

于 2012-09-20T16:01:53.390 回答