Jquery ajax调用webservice总结

2018-06-24 00:26:38来源:未知 阅读 ()

新老客户大回馈,云服务器低至5折

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

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:关于el-dialog,我更推荐的用法

下一篇:从“繁”到“简”进行数组去重