在撰寫$.ajax Call WebService時,常遇到需處理Exception,
若可以接收Exception的訊息,通知前端秀出訊息,就可以更好Debug或讓一些訊息可以給使用者觀看
在Js的部分:
<script src="../Scripts/json2.js" type="text/javascript"></script>
$.ajax({
type: 'POST',
url: 'WebService.asmx/GetJsonSend',
data: JsonText,
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: function (msg) {
var jsonData = eval("(" + msg.d + ")");
var gid =
"<table cellspacing='0' cellpadding='3 rules='cols' border='1' >" +
"<tr><th>ID</th><th>SN</th><th>Size</th></tr>";
$.each(jsonData, function (rec) {
gid += "<tr>";
gid += "<td>" + this.id + "</td><td>" + this.sn + "</td><td>" + this.size + "</td>";
gid += "</tr>";
});
gid += "</table>";
$(".panel").html(gid);
},
error: function (xhr, ajaxOptions, thrownError) {
// alert(xhr.statusText);
// alert(xhr.responseText);
//處理Exception訊息
var jsonData = JSON.parse(xhr.responseText);
$.each(jsonData, function (key, value) {
//接收Exception的訊息文字
if (key == 'Message') {
alert(value);
}
});
}
}); //** ajax End **//
WebService.cs部分
[WebMethod]
public string GetJsonSend(List <string > p_list ) {
String Sql = "Select * From tCustomer Where fName='"+p_list[0]+"'";
CSqlHelp l_Sh = new CSqlHelp();
DataTable l_dt = l_Sh.SelectAdapter(Sql);
if (l_dt.Rows.Count == 0)
throw new Exception("查無客戶資料!");
else
{
ArrayList list = new ArrayList();
CEn en1 = new CEn();
en1.id = "A1";
en1.size = "100";
en1.sn = "Ray";
CEn en2 = new CEn();
en2.id = "A2";
en2.size = "500";
en2.sn = "BigOne";
list.Add(en1);
list.Add(en2);
return GetJsonData(list);
}
}
private string GetJsonData(IList p_list)
{
JavaScriptSerializer JS = new JavaScriptSerializer();
return JS.Serialize(p_list);
}
若查無資料時,WebService會將Exception的相關資訊傳給ajax的error接收,
而在error中的xhr.responseText 設立中斷點,可以看到接收Json格式如下:
{"Message":"查無資料!"
,"StackTrace":" 於 WebService.GetJsonSend(List`1 p_list) 於 d:\\AjaxWeb\\App_Code\\WebService.cs: 行 30"
,"ExceptionType":"System.Exception"}
利用Json.parse();將其轉為物件,再利用Jquery.each輪巡,
就可以抓到Key為Message的Value,也就是我們在後端所拋出的Exception的訊息!
留言列表