2014-09-23 77 views
0

我从[WebMethod]返回List<strings>。但是当发生异常时如何将消息返回给AJAX调用者?现在我得到构建错误。如何从webmethod将异常返回到AJAX调用?

JS:

$.ajax({ 
    type: 'POST', 
    contentType: "application/json; charset=utf-8", 
    url: 'new.aspx/GetPrevious', 
    data: "{'name':'" + username + "'}", 
    async: false, 
    success: function (data) { 
     Previous = data.d; 
     alert(salts); 
    }, 
    error: function() { 
     alert("Error"); 
    } 
}); 

C#:

[WebMethod] 
public static List<string> GetPreviousSaltsAndHashes(string name) 
{ 
    try 
    { 
     List<string> prevSalts = new List<string>(); 
     if (reader.HasRows) 
     { 
      while (reader.Read()) 
      {      
       prevSalts.Add(reader.GetString(0)); 
      } 
     } 
     conn.Close(); 
     return prevSalts; 
    } 
    catch (Exception ex) 
    { 
     return "failure"; //error showing here 
    } 
} 

回答

0

确保您在这两种情况下返回相同的类型。你的失败更改到一个列表:

List<string> prevSalts = new List<string>(); 
try 
{ 
    ... 
} 
catch (Exception ex) 
{ 
    prevSalts.Clear(); 
    prevSalts.Add("failure");  
} 
return Json(new 
{ 
    salts = prevSalts 
}, JsonRequestBehavior.AllowGet); 

编辑:让你的琴弦在前端,检查它在适当的方法

success: function (data) { 
    Previous = data.salts 
    alert(salts); 
}, 
error: function (data) { 
    $.each(data.salts, function(index,item) { 
     alert(item); 
    }); 
} 
+0

但是我怎样才能捕捉错误:函数()在AJAX? – James123 2014-09-23 19:18:44

+0

看到我的新编辑 – 2014-09-23 23:49:19

2

所有异常从WebMethod扔得到自动序列化到响应作为.NET Exception实例的JSON表示。您可以结账following article了解更多详情。

所以,你的服务器端代码可能有点简单:

[WebMethod] 
public static List<string> GetPreviousSaltsAndHashes(string name) 
{ 
    List<string> prevSalts = new List<string>(); 

    // Note: This totally sticks. It's unclear what this reader instance is but if it is a 
    // SqlReader, as it name suggests, it should probably be wrapped in a using statement 
    if (reader.HasRows) 
    { 
     while (reader.Read()) 
     {      
      prevSalts.Add(reader.GetString(0)); 
     } 
    } 

    // Note: This totally sticks. It's unclear what this conn instance is but if it is a 
    // SqlConnection, as it name suggests, it should probably be wrapped in a using statement 
    conn.Close(); 

     return prevSalts; 
    } 
} 

,并在客户端:

error: function (xhr, status, error) { 
    var exception = JSON.parse(xhr.responseText); 
    // exception will contain all the details you might need. For example you could 
    // show the exception Message property 
    alert(exception.Message); 
} 

,并在一天结束的时候,他说这一切的东西后,你应该意识到WebMethods是一种完全过时和过时的技术,除非您维护一些现有的代码,否则绝对没有理由在新项目中使用它们。

0

您可以返回一个通用结构体(实际数据),状态码和错误字段来描述异常(如果有的话)。然后在JS方面,你只需要根据状态码使用正文或错误字段。这是我在我最后一次使用soap webservice中使用的。