【AngularJS】通过jsonp与webmethod交互,实现ajax验证

服务端配置

1:新建一个asp.net的网站

2: 创建一个服务文件:LoginService.asmx

注意:记得取消[System.Web.Script.Services.ScriptService]的注释

因为要使用jsonp来达到跨域访问,所以要声明输出类型和加上callback函数前缀。

using System.Web.Services;

namespace testService
{
    /// <summary>
    /// LoginService 的摘要说明
    /// </summary>
    [WebService(Namespace = "zhexian.com")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。
    [System.Web.Script.Services.ScriptService]
    public class LoginService : System.Web.Services.WebService
    {
        [WebMethod]
        public void CheckUserNameExist(string username)
        {
            Context.Response.ContentType = "application/x-javascript";
            string result = username == "kimmy" ? "true" : "false";
            string callBackName = Context.Request.QueryString["callback"];
            Context.Response.Write(callBackName + "({\"isUnique\":\"" + result + "\"})");
        }
    }
}

3:配置web.config

在web.config, <system.web>下,加入字段

 <webServices>
      <protocols>
        <add name="HttpPost"/>
        <add name="HttpGet"/>
      </protocols>
    </webServices>

 

网页配置

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>入门入门</title>
<link rel="stylesheet" href="http://cdn.jsdelivr.net/foundation/4.3.2/css/foundation.min.css">
<style type="text/css">
</style>
</head>
<body ng-app="myApp">
<form name="singnupForm" novalidate ng-submit="signupForm()">
<fieldset>
    <legend>注册</legend>
 <div>

  <div class="row">
      <div class="large-12 columns">
          
          <input type="text" placeholder="用户名" name="name" ng-model="user.name" ng-minlength="2" ng-maxlength="20" ensure-unique="name"  required />

      <div class="error" ng-show="singnupForm.name.$dirty && singnupForm.name.$invalid">
          <small class="error" ng-show="singnupForm.name.$error.required">
              请录入用户名
          </small>
       <small class="error" ng-show="singnupForm.name.$error.minlength">
        最少2个字符
       </small>
       <small class="error" ng-show="singnupForm.name.$error.maxlength">
           最多20个字符
       </small>
       <small class="error" ng-show="singnupForm.name.$error.unique">
           用户名已经存在
       </small>
      </div>
  </div>
  </div>

  <div class="row">
      <div class="large-12 columns">
  <input type="password" placeholder="密码" name="pwd" ng-model="user.pwd" ng-minlength="5" required />
      <div class="error" ng-show="singnupForm.pwd.$dirty && singnupForm.pwd.$invalid">
      <small class="error" ng-show="singnupForm.pwd.$error.required">
              请录入密码
          </small>
       <small class="error" ng-show="singnupForm.pwd.$error.minlength">
        最少5个字符
       </small>
      </div>
      </div>
 </div>

<div class="row">
      <div class="large-12 columns">
      <input type="email" placeholder="邮件地址" name="email" ng-model="user.email" ng-minlength="5" ng-maxlength="20" required />
   <div class="error" ng-show="singnupForm.email.$dirty && singnupForm.email.$invalid">
      <small clss="error" ng-show="singnupForm.email.$error.required">
          请录入邮件地址
      </small>
      <small class="error" ng-show="singnupForm.email.$error.email">
          邮件地址不正确
      </small>
      <small class="error" ng-show="singnupForm.email.$error.minlength">
          最少3个字符
      </small>
      <small class="error" ng-show="singnupForm.email.$error.maxlength">
          最长20个字符
      </small>
  </div>
 </div>
 </div>

<div class="row">
      <div class="large-12 columns">
      <input type="number" placeholder="年龄" name="age" ng-model="user.age" ng-minlength="1" required />
   <div class="error" ng-show="singnupForm.age.$dirty && singnupForm.age.$invalid">
      <small clss="error" ng-show="singnupForm.age.$error.required">
          请录入年龄
      </small>
      <small class="error" ng-show="singnupForm.age.$error.number">
          年龄格式不正确
      </small>
  </div>
  <button type="submit" ng-disabled="singnupForm.$invalid" class="button radius">submit</button>
 </div>
 </div>

</fieldset>
</form>
<script src="angular.min.js"></script>
</body>
</html>

JS部分,加在Body前面

<script type="text/javascript">
    var myApp = angular.module(‘myApp‘,[]);

    myApp.directive(‘ensureUnique‘,function ($http) {

         return {
             require:‘ngModel‘,
             link:function(scope,ele,attrs,c){
               scope.$watch(attrs.ngModel,function (n) {

                   if (!n) 
                       return;

             $http.jsonp(
                ‘http://192.168.18.114:3301/LoginService.asmx/CheckUserNameExist?callback=JSON_CALLBACK‘,
                {
                    params  :{‘username‘:scope.user.name}
                }
               ).success(function (data) {
               var isUnique = data && data.isUnique && data.isUnique.toLowerCase()=="true";

                   c.$setValidity(‘unique‘,isUnique);
               }).error(function  (data) {
               
                    c.$setValidity(‘unique‘,false);
               });
             });
          }
         };
    });
</script>

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。