jquery ajax調用webservice(C#)要註意的幾個事項: 1、web.config里需要配置2個地方 <httpHandlers> <remove verb="*" path="*.asmx"/> <add verb="*" path="*.asmx" validate="false ...
jquery ajax調用webservice(C#)要註意的幾個事項:
1、web.config里需要配置2個地方
<httpHandlers>
<remove verb="*" path="*.asmx"/>
<add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</httpHandlers>
在<system.web></system.web>之間加入
<webServices>
<protocols>
<add name="HttpPost" />
<add name="HttpGet" />
</protocols>
</webServices>
2.正確地編寫webserivce的代碼
1 /// <summary> 2 /// UserValidate 的摘要說明 3 /// </summary> 4 [WebService(Namespace = "http://tempuri.org/")] 5 [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] 6 [System.ComponentModel.ToolboxItem(false)] 7 // 若要允許使用 ASP.NET AJAX 從腳本中調用此 Web 服務,請取消對下行的註釋。 8 [System.Web.Script.Services.ScriptService] 9 public class UserValidate : System.Web.Services.WebService 10 { 11 DFHon.Content.Common.rootPublic rp = new DFHon.Content.Common.rootPublic(); 12 [WebMethod] 13 [ScriptMethod(ResponseFormat = ResponseFormat.Json)] 14 public string ValidateUserLogState() 15 { 16 string result = ""; 17 HttpCookie cookie = HttpContext.Current.Request.Cookies["DHFonMenberInfo"]; 18 if (cookie != null) 19 { 20 string username = System.Web.HttpUtility.UrlDecode(cookie["MenberName"]); 21 int ipoint = 0; 22 int gpoint = 0; 23 try 24 { 25 DataTable dt = UserBll.ExecuteUserAllInfo(username); 26 27 if (dt.Rows.Count > 0) 28 { 29 ipoint = int.Parse(dt.Rows[0]["iPoint"].ToString()); 30 gpoint = int.Parse(dt.Rows[0]["gPoint"].ToString()); 31 } 32 } 33 catch 34 { } 35 result = "{'user':{'id':'" + cookie["UserId"] + "','name':'" + username + "','message':'" + rp.getUserMsg(DFHon.Global.CurrentCookie.UserName) + "','ipoint':'" + ipoint.ToString() + "','gpoint':'" + gpoint.ToString() + "'}}"; 36 } 37 else 38 { 39 result = "{'user':{'id':'0','name':'','message':'0','ipoint':'0','gpoint':'0'}}"; 40 } 41 return result; 42 } 43 44 [WebMethod] 45 [ScriptMethod(ResponseFormat = ResponseFormat.Json)] 46 public string UserLogin(string userName, string userPwd) 47 { 48 string returnVal = ""; 49 try 50 { 51 GlobalUserInfo info; 52 DFHon.Content.UserLogin _UserLogin = new DFHon.Content.UserLogin(); 53 EnumLoginState state = _UserLogin.PersonLogin(HttpUtility.UrlDecode(userName), userPwd, out info); 54 if (state == EnumLoginState.Succeed) 55 { 56 DFHon.Global.CurrentCookie.Set(info); 57 DFHon.API.PDO.DiscuzNT.PassportLogin.UserLogin(Server.UrlDecode(userName), userPwd, -1); 58 int ipoint = 0; 59 int gpoint = 0; 60 DataTable dt = UserBll.ExecuteUserAllInfo(userName); 61 62 if (dt.Rows.Count > 0) 63 { 64 ipoint = int.Parse(dt.Rows[0]["iPoint"].ToString()); 65 gpoint = int.Parse(dt.Rows[0]["gPoint"].ToString()); 66 } 67 returnVal = "{'user':{'id':'" + info.UserId.ToString() + "','name':'" + info.UserName + "','message':'" + rp.getUserMsg(userName) + "','ipoint':'" + ipoint.ToString() + "','gpoint':'" + gpoint.ToString() + "'}}"; 68 } 69 else 70 { 71 int ids = 0;//狀態:-2用戶被鎖定 -1用戶名密碼錯誤 72 switch (state) 73 { 74 case EnumLoginState.Err_Locked: 75 ids = -2; 76 break; 77 case EnumLoginState.Err_UserNameOrPwdError: 78 ids = -1; 79 break; 80 default: 81 break; 82 } 83 returnVal = "{'user':{'id':'" + ids + "','name':'','message':'0','ipoint':'0','gpoint':'0'}}"; 84 } 85 } 86 catch 87 { 88 returnVal = "{'user':{'id':'0','name':'','message':'0','ipoint':'0','gpoint':'0'}}"; 89 } 90 return returnVal; 91 } 92 [WebMethod] 93 public string UserLogout() 94 { 95 if (HttpContext.Current.Request.Cookies["DHFonMenberInfo"] != null) 96 { 97 HttpCookie cookie = new HttpCookie("DHFonMenberInfo"); 98 cookie.Expires = System.DateTime.Now.AddDays(-1); 99 cookie.Domain = DFHon.Config.BaseConfig.getV("weblogin"); 100 HttpContext.Current.Response.AppendCookie(cookie); 101 } 102 return "1"; 103 } 104 DFHon.Content.user UserBll = new DFHon.Content.user(); 105 [WebMethod] 106 public string ValidateUserEmail(string email) 107 { 108 string result = "0";//返回的結果 -2郵箱為空 -1郵箱格式不正確 0郵箱存在 1填寫正確 109 if (string.IsNullOrEmpty(email)) 110 { 111 result = "-2";//郵箱為空 112 } 113 else if (!IsValidEmail(email)) 114 { 115 result = "-1";//郵箱格式不正確 116 } 117 else if (UserBll.sel_useremail(email) > 0) 118 { 119 result = "0";//郵箱存在 120 } 121 else 122 { 123 result = "1";//可以註冊 124 } 125 return result; 126 } 127 128 [WebMethod] 129 public string ValidateUserName(string username) 130 { 131 string result = "0";//返回值:-1用戶名長度為2-16;0用戶名存在;1可以註冊 132 if (username == "" || username == null || username.Length < 2 || username.Length > 16) 133 { 134 result = "-1"; 135 } 136 else if (UserBll.sel_username(username) != 0) 137 { 138 result = "0"; 139 } 140 else 141 { 142 result = "1"; 143 } 144 return result; 145 } 146 147 public bool IsValidEmail(string strIn) 148 { // Return true if strIn is in valid e-mail format. 149 return System.Text.RegularExpressions.Regex.IsMatch(strIn, @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$"); 150 } 151 }WebService
1 <script> 2 $(function() { 3 $("#userloging").show(); 4 //登錄框處理開始 5 //載入登錄狀態 6 $.ajax({ 7 type: "POST", //訪問WebService使用Post方式請求 8 contentType: "application/json;charset=utf-8", //WebService 會返回Json類型 9 url: "/API/Service/UserValidate.asmx/ValidateUserLogState", //調用WebService 10 data: "{}", //Email參數 11 dataType: 'json', 12 beforeSend: function(x) { x.setRequestHeader("Content-Type", "application/json; charset=utf-8"); }, 13 error: function(x, e) { }, 14 success: function(response) { //回調函數,result,返回值 15 $("#userloging").hide(); 16 var json = eval('(' + response.d + ')'); 17 var userid = json.user.id; 18 if (userid > 0) { 19 $("#spanusername").html(json.user.name); 20 $("#spanmessagenum").html(json.user.message); 21 $("#userloginsucced").show(); 22 $("#userloginbox").hide(); 23 } 24 } 25 }); 26 //登錄 27 $("#userlogbutton").click(function() { 28 29 var username = $("#username").val(); 30 var userpwd = $("#userpassword").val(); 31 if (username != "" && userpwd != "") { 32 $("#userloging").show(); 33 $.ajax({ 34 type: "POST", //訪問WebService使用Post方式請求 35 contentType: "application/json;charset=utf-8", //WebService 會返回Json類型 36 url: "/API/Service/UserValidate.asmx/UserLogin", //調用WebService 37 data: "{userName:'" + username + "',userPwd:'" + userpwd + "'}", //Email參數 38 dataType: 'json', 39 beforeSend: function(x) { x.setRequestHeader("Content-Type", "application/json; charset=utf-8"); }, 40 error: function(x, e) { 41 }, 42 success: function(result) { //回調函數,result,返回值 43 $("#userloging").hide(); 44 var json = eval('(' + result.d + ')'); 45 var userid = json.user.id; 46 if (userid > 0) { 47 $("#spanusername").html(json.user.name); 48 $("#spanmessagenum").html(json.user.message); 49 $("#userloginsucced").show(); 50 $("#userloginbox").hide(); 51 } 52 else { 53 switch (userid) { 54 case -2: 55 alert("用戶被鎖定!請30分鐘後再登錄!"); 56 $("#username").focus(); 57 break; 58 case -1: 59 alert("用戶名或密碼錯誤!請核對您的用戶名和密碼!"); 60 $("#userpassword").focus(); 61 break; 62 default: 63 alert("登錄失敗!請核對您的用戶名和密碼之後重試!"); 64 $("#userpassword").focus(); 65 break; 66 } 67 } 68 } 69 }); 70 } 71 else if (username == "") { 72 alert("用戶名不能為空!"); 73 $("#username").focus(); 74 } 75 else if (userpwd == "") { 76 alert("密碼不能為空!"); 77 $("#userpassword").focus(); 78 } 79 }); 80 //退出 81 $("#logout").click(function() { 82 $("#userloging").show(); 83 $.ajax({ 84 type: "POST", //訪問WebService使用Post方式請求 85 contentType: "application/json;utf-8", //WebService 會返回Json類型 86 url: "/API/Service/UserValidate.asmx/UserLogout", //調用WebService 87 data: "{}", //Email參數 88 dataType: 'json', 89 beforeSend: function(x) { x.setRequestHeader("Content-Type", "application/json; charset=utf-8"); }, 90 success: function(result) { //回調函數,result,返回值 91 $("#userloging").hide(); 92 if (result.d > 0) { 93 $("#userloginsucced").hide(); 94 $("#userloginbox").show(); 95 } 96 } 97 }); 98 99 }); //登錄框處理結束 100 101 }); 102 </script>ajax