当前位置:Gxlcms > JavaScript > jQuery ajax调用webservice注意事项

jQuery ajax调用webservice注意事项

时间:2021-07-01 10:21:17 帮助过:50人阅读

jquery ajax调用webservice(C#)要注意的几个事项:

1、web.config里需要配置2个地方

  1. <httpHandlers>
  2. <remove verb="*" path="*.asmx"/>
  3. <add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
  4. </httpHandlers>

在<system.web></system.web>之间加入

  1. <webServices>
  2. <protocols>
  3. <add name="HttpPost" />
  4. <add name="HttpGet" />
  5. </protocols>
  6. </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. if (dt.Rows.Count > 0)
  27. {
  28. ipoint = int.Parse(dt.Rows[0]["iPoint"].ToString());
  29. gpoint = int.Parse(dt.Rows[0]["gPoint"].ToString());
  30. }
  31. }
  32. catch
  33. { }
  34. result = "{'user':{'id':'" + cookie["UserId"] + "','name':'" + username + "','message':'" + rp.getUserMsg(DFHon.Global.CurrentCookie.UserName) + "','ipoint':'" + ipoint.ToString() + "','gpoint':'" + gpoint.ToString() + "'}}";
  35. }
  36. else
  37. {
  38. result = "{'user':{'id':'0','name':'','message':'0','ipoint':'0','gpoint':'0'}}";
  39. }
  40. return result;
  41. }
  42. [WebMethod]
  43. [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
  44. public string UserLogin(string userName, string userPwd)
  45. {
  46. string returnVal = "";
  47. try
  48. {
  49. GlobalUserInfo info;
  50. DFHon.Content.UserLogin _UserLogin = new DFHon.Content.UserLogin();
  51. EnumLoginState state = _UserLogin.PersonLogin(HttpUtility.UrlDecode(userName), userPwd, out info);
  52. if (state == EnumLoginState.Succeed)
  53. {
  54. DFHon.Global.CurrentCookie.Set(info);
  55. DFHon.API.PDO.DiscuzNT.PassportLogin.UserLogin(Server.UrlDecode(userName), userPwd, -1);
  56. int ipoint = 0;
  57. int gpoint = 0;
  58. DataTable dt = UserBll.ExecuteUserAllInfo(userName);
  59. if (dt.Rows.Count > 0)
  60. {
  61. ipoint = int.Parse(dt.Rows[0]["iPoint"].ToString());
  62. gpoint = int.Parse(dt.Rows[0]["gPoint"].ToString());
  63. }
  64. returnVal = "{'user':{'id':'" + info.UserId.ToString() + "','name':'" + info.UserName + "','message':'" + rp.getUserMsg(userName) + "','ipoint':'" + ipoint.ToString() + "','gpoint':'" + gpoint.ToString() + "'}}";
  65. }
  66. else
  67. {
  68. int ids = 0;//状态:-2用户被锁定 -1用户名密码错误
  69. switch (state)
  70. {
  71. case EnumLoginState.Err_Locked:
  72. ids = -2;
  73. break;
  74. case EnumLoginState.Err_UserNameOrPwdError:
  75. ids = -1;
  76. break;
  77. default:
  78. break;
  79. }
  80. returnVal = "{'user':{'id':'" + ids + "','name':'','message':'0','ipoint':'0','gpoint':'0'}}";
  81. }
  82. }
  83. catch
  84. {
  85. returnVal = "{'user':{'id':'0','name':'','message':'0','ipoint':'0','gpoint':'0'}}";
  86. }
  87. return returnVal;
  88. }
  89. [WebMethod]
  90. public string UserLogout()
  91. {
  92. if (HttpContext.Current.Request.Cookies["DHFonMenberInfo"] != null)
  93. {
  94. HttpCookie cookie = new HttpCookie("DHFonMenberInfo");
  95. cookie.Expires = System.DateTime.Now.AddDays(-1);
  96. cookie.Domain = DFHon.Config.BaseConfig.getV("weblogin");
  97. HttpContext.Current.Response.AppendCookie(cookie);
  98. }
  99. return "1";
  100. }
  101. DFHon.Content.user UserBll = new DFHon.Content.user();
  102. [WebMethod]
  103. public string ValidateUserEmail(string email)
  104. {
  105. string result = "0";//返回的结果 -2邮箱为空 -1邮箱格式不正确 0邮箱存在 1填写正确
  106. if (string.IsNullOrEmpty(email))
  107. {
  108. result = "-2";//邮箱为空
  109. }
  110. else if (!IsValidEmail(email))
  111. {
  112. result = "-1";//邮箱格式不正确
  113. }
  114. else if (UserBll.sel_useremail(email) > 0)
  115. {
  116. result = "0";//邮箱存在
  117. }
  118. else
  119. {
  120. result = "1";//可以注册
  121. }
  122. return result;
  123. }
  124. [WebMethod]
  125. public string ValidateUserName(string username)
  126. {
  127. string result = "0";//返回值:-1用户名长度为2-16;0用户名存在;1可以注册
  128. if (username == "" || username == null || username.Length < 2 || username.Length > 16)
  129. {
  130. result = "-1";
  131. }
  132. else if (UserBll.sel_username(username) != 0)
  133. {
  134. result = "0";
  135. }
  136. else
  137. {
  138. result = "1";
  139. }
  140. return result;
  141. }
  142. public bool IsValidEmail(string strIn)
  143. { // Return true if strIn is in valid e-mail format.
  144. 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})(\]?)$");
  145. }
  146. }

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. var username = $("#username").val();
  29. var userpwd = $("#userpassword").val();
  30. if (username != "" && userpwd != "") {
  31. $("#userloging").show();
  32. $.ajax({
  33. type: "POST", //访问WebService使用Post方式请求
  34. contentType: "application/json;charset=utf-8", //WebService 会返回Json类型
  35. url: "/API/Service/UserValidate.asmx/UserLogin", //调用WebService
  36. data: "{userName:'" + username + "',userPwd:'" + userpwd + "'}", //Email参数
  37. dataType: 'json',
  38. beforeSend: function(x) { x.setRequestHeader("Content-Type", "application/json; charset=utf-8"); },
  39. error: function(x, e) {
  40. },
  41. success: function(result) { //回调函数,result,返回值
  42. $("#userloging").hide();
  43. var json = eval('(' + result.d + ')');
  44. var userid = json.user.id;
  45. if (userid > 0) {
  46. $("#spanusername").html(json.user.name);
  47. $("#spanmessagenum").html(json.user.message);
  48. $("#userloginsucced").show();
  49. $("#userloginbox").hide();
  50. }
  51. else {
  52. switch (userid) {
  53. case -2:
  54. alert("用户被锁定!请30分钟后再登录!");
  55. $("#username").focus();
  56. break;
  57. case -1:
  58. alert("用户名或密码错误!请核对您的用户名和密码!");
  59. $("#userpassword").focus();
  60. break;
  61. default:
  62. alert("登录失败!请核对您的用户名和密码之后重试!");
  63. $("#userpassword").focus();
  64. break;
  65. }
  66. }
  67. }
  68. });
  69. }
  70. else if (username == "") {
  71. alert("用户名不能为空!");
  72. $("#username").focus();
  73. }
  74. else if (userpwd == "") {
  75. alert("密码不能为空!");
  76. $("#userpassword").focus();
  77. }
  78. });
  79. //退出
  80. $("#logout").click(function() {
  81. $("#userloging").show();
  82. $.ajax({
  83. type: "POST", //访问WebService使用Post方式请求
  84. contentType: "application/json;utf-8", //WebService 会返回Json类型
  85. url: "/API/Service/UserValidate.asmx/UserLogout", //调用WebService
  86. data: "{}", //Email参数
  87. dataType: 'json',
  88. beforeSend: function(x) { x.setRequestHeader("Content-Type", "application/json; charset=utf-8"); },
  89. success: function(result) { //回调函数,result,返回值
  90. $("#userloging").hide();
  91. if (result.d > 0) {
  92. $("#userloginsucced").hide();
  93. $("#userloginbox").show();
  94. }
  95. }
  96. });
  97. }); //登录框处理结束
  98. });
  99. </script>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

人气教程排行