最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

詳細分析使用AngularJS編程中提交表單的方式

 更新時間:2015年06月19日 10:34:14   投稿:goldensun  
這篇文章主要介紹了詳細分析使用AngularJS提交表單的方式,AngularJS是非常熱門的JavaScript庫,文中展示了AngularJS在前端與后端的PHP進行交互的場景,需要的朋友可以參考下

在AngularJS出現(xiàn)之前,很多開發(fā)者就面對了表單提交這一問題。由于提交表單的方式繁雜而不同,很容易令人瘋掉……然而現(xiàn)在看來,依然會讓人瘋掉。

今天,我們會看一下過去使用PHP方式提交的表單,現(xiàn)在如何將其轉換為使用Angular提交。使用Angular來處理表單,對我而言,是一個“啊哈”時刻(譯者:表示了解或發(fā)現(xiàn)某事物的喜悅)。即使它甚至都沒有涉及多少Angular表層的東西,但是它卻幫助用戶看到表單提交之后的潛力,并且理解兩種數據綁定方式。

我們會使用jQuery平臺來進行這個處理過程。所以所要做的工作首先使用javascript。我們會提交表單,展示錯誤信息,添加錯誤類,并且在javascript中顯示和隱藏信息。


之后,我們會使用Angular。在使用之前,我們要做大部分所需的工作,并且我們之前所做的很多工作會非常容易。讓我們開始吧。

簡單的表單

我們會關注兩種提交表單的方式:

  •     舊方法:jQuery和PHP提交表單
  •     新方法:AngularJS和PHP提交表單

首先看一下我們的表單,超級簡單:

2015619102411460.jpg (800×400)

形式要求

  •     實現(xiàn)頁面無刷新表單處理
  •     輸入姓名和超級英雄別名
  •     如果有錯誤,顯示錯誤提示
  •     如果輸入有誤,將輸入變成紅色
  •     如果所有內容ok,顯示成功提示

文檔結構

在我們的展示中,僅需兩個文件

  •     index.html
  •     process.php

 
表單處理

讓我們新建一個PHP來處理表單。該頁面非常小并且使用POST方式提交數據。

處理表單:這對我們來說并不是那么重要的。你可以使用其他你喜歡的語言來處理你的表單。
 

// process.php
 
<?php
 
$errors   = array();  // array to hold validation errors
$data    = array();   // array to pass back data
 
// validate the variables ======================================================
 if (empty($_POST['name']))
  $errors['name'] = 'Name is required.';
 
 if (empty($_POST['superheroAlias']))
  $errors['superheroAlias'] = 'Superhero alias is required.';
 
// return a response ===========================================================
 
 // response if there are errors
 if ( ! empty($errors)) {
 
  // if there are items in our errors array, return those errors
  $data['success'] = false;
  $data['errors'] = $errors;
 } else {
 
  // if there are no errors, return a message
  $data['success'] = true;
  $data['message'] = 'Success!';
 }
 
 // return all our data to an AJAX call
 echo json_encode($data);

這是一個非常簡單的表單處理腳本。我們僅檢查數據是否存在,如果存在,則不做任何處理和操做;如果不存在,則需要向$errors數組中添加一條信息。

為了返回我們的數據用于AJAX調用,我們需要使用echo和json_encode。這就是我們PHP表單處理所有需要做的操作。使用普通的jQuery AJAX或者Angular處理表單也是這樣的。
 展示表單

讓我們創(chuàng)建一個HTML來展示我們的表單

<!-- index.html -->
 
<!doctype html>
<html>
<head>
 <title>Angular Forms</title>
 
 <!-- LOAD BOOTSTRAP CSS -->
 <link rel="stylesheet" >
 
 <!-- LOAD JQUERY -->
  <!-- when building an angular app, you generally DO NOT want to use jquery -->
  <!-- we are breaking this rule here because jQuery's $.param will help us send data to our PHP script so that PHP can recognize it -->
  <!-- this is jQuery's only use. avoid it in Angular apps and if anyone has tips on how to send data to a PHP script w/o jQuery, please state it in the comments -->
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
 
 <!-- PROCESS FORM WITH AJAX (OLD) -->
 <script>
  <!-- WE WILL PROCESS OUR FORM HERE -->
 </script>
</head>
<body>
<div class="container">
<div class="col-md-6 col-md-offset-3">
 
 <!-- PAGE TITLE -->
 <div class="page-header">
  <h1><span class="glyphicon glyphicon-tower"></span> Submitting Forms with Angular</h1>
 </div>
 
 <!-- SHOW ERROR/SUCCESS MESSAGES -->
 <div id="messages"></div>
 
 <!-- FORM -->
 <form>
  <!-- NAME -->
  <div id="name-group" class="form-group">
   <label>Name</label>
   <input type="text" name="name" class="form-control" placeholder="Bruce Wayne">
   <span class="help-block"></span>
  </div>
 
  <!-- SUPERHERO NAME -->
  <div id="superhero-group" class="form-group">
   <label>Superhero Alias</label>
   <input type="text" name="superheroAlias" class="form-control" placeholder="Caped Crusader">
   <span class="help-block"></span>
  </div>
 
  <!-- SUBMIT BUTTON -->
  <button type="submit" class="btn btn-success btn-lg btn-block">
   <span class="glyphicon glyphicon-flash"></span> Submit!
  </button>
 </form>
 
</div>
</div>
</body>
</html>

現(xiàn)在,我們有了表單。我們另外還使用了Bootstrap來使表單看起來不是那么丑。使用Bootstrap語法規(guī)則,每個input下含有一個spot來展示我們文本的錯誤信息。

2015619102451118.jpg (800×400)

使用jQuery提交表單

現(xiàn)在,讓我們來使用jQuery處理表單提交。我會將所有的代碼添加到空的<script>標簽中
 

<!-- index.html -->
 
...
 
 <!-- PROCESS FORM WITH AJAX (OLD) -->
 <script>
  $(document).ready(function() {
 
   // process the form
   $('form').submit(function(event) {
 
    // remove the past errors
    $('#name-group').removeClass('has-error');
    $('#name-group .help-block').empty();
    $('#superhero-group').removeClass('has-error');
    $('#superhero-group .help-block').empty();
 
    // remove success messages
    $('#messages').removeClass('alert alert-success').empty();
 
    // get the form data
    var formData = {
     'name'     : $('input[name=name]').val(),
     'superheroAlias'  : $('input[name=superheroAlias]').val()
    };
 
    // process the form
    $.ajax({
     type   : 'POST',
     url   : 'process.php',
     data   : formData,
     dataType  : 'json',
     success  : function(data) {
 
      // log data to the console so we can see
      console.log(data);
 
      // if validation fails
      // add the error class to show a red input
      // add the error message to the help block under the input
      if ( ! data.success) {
 
       if (data.errors.name) {
        $('#name-group').addClass('has-error');
        $('#name-group .help-block').html(data.errors.name);
       }
 
       if (data.errors.superheroAlias) {
        $('#superhero-group').addClass('has-error');
        $('#superhero-group .help-block').html(data.errors.superheroAlias);
       }
 
      } else {
 
       // if validation is good add success message
       $('#messages').addClass('alert alert-success').append('<p>' + data.message + '</p>');
      }
     }
    });
 
    // stop the form from submitting and refreshing
    event.preventDefault();
   });
 
  });
 </script>
 
...

這里處理表單有不少的代碼。我們有獲取表單中變量的代碼,有使用AJAX將數據發(fā)送至我們的表單的代碼,有檢查是否有錯和顯示成功提示的代碼。除此之外,我們希望每次表單提交之后,過去的錯誤信息都會被清除。確實是不少代碼。

現(xiàn)在,如果表單中含有錯誤,則:

2015619102537437.jpg (800×400)

如果提交成功:

2015619102608037.jpg (800×400)

現(xiàn)在,讓我們看使用Angular來提交相同的表單。記住,我們不需要更改任何關于我們的PHP如何處理表單的內容,我們的應用依然會具備相同的功能(在同一個地方展示錯誤和成功信息)。

使用Angular提交表單

我們準備在之前使用的<script>標簽中設置我們的Angular應用。所以刪除里面的內容,我們就可以開始了。
設置一個Angular應用

步驟為:

    1. 加載Angular

    2. 設置module

    3. 這是controller

    4. 將module和controller應用于HTML

    5. 設置雙向變量綁定

    6. 這是錯誤和信息

看起來好像是很多內容,但是最終,我們會用非常少的代碼,并且看起來會非常簡潔。另外,創(chuàng)建帶有更多輸入更大的表單,也會更容易。

Angular 組件和控制器

首先,加載Angular并且新建組件和控制器
 

<!-- index.html -->
 
...
 
 <!-- LOAD JQUERY -->
 <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
 <!-- LOAD ANGULAR -->
 <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>
 
 <!-- PROCESS FORM WITH AJAX (NEW) -->
 <script>
 
  // define angular module/app
  var formApp = angular.module('formApp', []);
 
  // create angular controller and pass in $scope and $http
  function formController($scope, $http) {
 
  }
 
 </script>
</head>
 
<!-- apply the module and controller to our body so angular is applied to that -->
<body ng-app="formApp" ng-controller="formController">
 
...

現(xiàn)在,我們有了Angular應用的基礎。我們已經加載了Angular,創(chuàng)建了組件模塊和控制器,并且將其應用于我們的網站。

接下來,我將展示雙向綁定是如何工作的。

雙向數據綁定

這是Angular的核心思想之一,也是功能最強大的內容之一。在

我們在Angular中將數據和變量綁定在一起,無論是javascript也好,view也罷,只要有改變,兩者皆變。

為了演示數據綁定,我們需要獲取表單的input來自動填充變量formData。讓我們回到應用于頁面的Angular控制器中。我們在過一下$scope和$http。

$scope:控制器和視圖層之間的粘合劑。基本上,變量使用$scope從我們的控制器和視圖層之間傳遞和往來。具體詳細的定義,請參見文檔。

$http:Angular服務來幫助我們處理POST請求。更多信息,請參見文檔。

使用數據綁定獲取變量

好了,閑話少說。我們將這些討論應用到表單中去。方法比上面討論的要簡單。我們想Angular控制器和視圖中分別添加一行。
 

<!-- index.html -->
 
...
 
 <!-- PROCESS FORM WITH AJAX (NEW) -->
 <script>
 
  // define angular module/app
  var formApp = angular.module('formApp', []);
 
  // create angular controller and pass in $scope and $http
  function formController($scope, $http) {
 
   // create a blank object to hold our form information
   // $scope will allow this to pass between controller and view
   $scope.formData = {};
 
  }
 
...

現(xiàn)在,我們已經建立了一個formData對象。讓我們用表單數據來填充它。在顯示調用每個輸入和獲得val()之前,我們用ng-model綁定一個特殊的輸入到變量。
 

<!-- index.html -->
 
...
 
 <!-- FORM -->
 <form>
  <!-- NAME -->
  <div id="name-group" class="form-group">
   <label>Name</label>
   <input type="text" name="name" class="form-control" placeholder="Bruce Wayne" ng-model="formData.name">
   <span class="help-block"></span>
  </div>
 
  <!-- SUPERHERO NAME -->
  <div id="superhero-group" class="form-group">
   <label>Superhero Alias</label>
   <input type="text" name="superheroAlias" class="form-control" placeholder="Caped Crusader" ng-model="formData.superheroAlias">
   <span class="help-block"></span>
  </div>
 
  <!-- SUBMIT BUTTON -->
  <button type="submit" class="btn btn-success btn-lg btn-block">
   <span class="glyphicon glyphicon-flash"></span> Submit!
  </button>
 </form>
 
 <!-- SHOW DATA FROM INPUTS AS THEY ARE BEING TYPED -->
 <pre>
  {{ formData }}
 </pre>
 
...

現(xiàn)在,既然Angular已經將每個輸入綁到了formData。 當你輸入每個輸入框,你可以看到formData對象被填充了!有沒有很酷!

你不必在view中使用$scope。一切被認為是嵌入到$scope中的。
 
處理表單

在我們的舊表單中,我們使用jQuery提交表單,像這樣$('form').submit()?,F(xiàn)在我們使用Angular稱作ng-submit的特性。要想完成這個,我們需要添加一個控制器函數來處理表單,然后告訴我們form使用這個控制器函數:
 

<!-- index.html -->
 
...
 
 <!-- PROCESS FORM WITH AJAX (NEW) -->
 <script>
 
  // define angular module/app
  var formApp = angular.module('formApp', []);
 
  // create angular controller and pass in $scope and $http
  function formController($scope, $http) {
 
   // create a blank object to hold our form information
   // $scope will allow this to pass between controller and view
   $scope.formData = {};
 
   // process the form
   $scope.processForm = function() {
 
   };
 
  }
 
...
 
 <!-- FORM -->
 <form ng-submit="processForm()">
 
...

現(xiàn)在我們的form知道提交時使用控制器函數了。既然已經到位了,然我們用$http來處理表單吧。

處理表單的語法看起來跟原始方式很像。好處是我們不需要手動抓取表單數據,或者注入,隱藏,添加類顯示錯誤或成功信息。
 

<!-- index.html -->
 
...
 
// process the form
$scope.processForm = function() {
 $http({
  method : 'POST',
  url  : 'process.php',
  data : $.param($scope.formData), // pass in data as strings
  headers : { 'Content-Type': 'application/x-www-form-urlencoded' } // set the headers so angular passing info as form data (not request payload)
 })
  .success(function(data) {
   console.log(data);
 
   if (!data.success) {
    // if not successful, bind errors to error variables
    $scope.errorName = data.errors.name;
    $scope.errorSuperhero = data.errors.superheroAlias;
   } else {
    // if successful, bind success message to message
    $scope.message = data.message;
   }
  });
};
 
...

這就是我們的表單!沒有添加或移除類。我們需要每次提交表單時都清楚錯誤。我們只需綁定變量和需要用到的視圖。這非常棒,因為處理器用來處理數據,而視圖用來顯示數據.


jQuery POST vs Angular POST

有時能看到用POST方式提交在服務器中看不到數據,這是因為jQuery和Angular的序列化和發(fā)送數據的方式不同。這歸結于你所使用的服務器語言和它理解Angular提交的數據的能力。

上面的代碼是應用于PHP服務器的,jQuery對于$.param函數則是必需的。雖然實現(xiàn)上文中提到的內容有非常多不使用jQuery的方法,但在本實例中,使用jQuery的唯一原因就是,它更簡單。

下面簡潔的語法將會基于你服務器端語言來工作。

簡潔語法

這個例子是以字符串的方式發(fā)送數據,并且發(fā)送你的頭信息。如果你不需要這些,并且希望Angular 的$http POST盡可能的簡潔,我們可以使用簡寫方法:
 

...
 $http.post('process.php', $scope.formData)
  .success(function(data) {
   ...
  });
...

絕對更簡潔更容易記住方法。

$http 內部控制器: 理想的,你可以將$http請求從controller移除到 service.這只是為了演示目的,我們將會盡快在service上進行討論.

在視圖中顯示錯誤和信息

我們將使用指令ng-show和ng-class來處理我們的視圖,Angular雙方括號允許我們將變量放置在我們需要的地方。

  • ng-show: 根據變量值是否存在來顯示或隱藏元素. 文檔
  • ng-class: 根據變量值是否存在(或一些其他表達式)來添加或移除類. 文檔
<!-- index.html -->
 
...
 
 <!-- SHOW ERROR/SUCCESS MESSAGES -->
 <div id="messages" ng-show="message">{{ message }}</div>
 
 <!-- FORM -->
 <form>
  <!-- NAME -->
  <div id="name-group" class="form-group" ng-class="{ 'has-error' : errorName }">
   <label>Name</label>
   <input type="text" name="name" class="form-control" placeholder="Bruce Wayne">
   <span class="help-block" ng-show="errorName">{{ errorName }}</span>
  </div>
 
  <!-- SUPERHERO NAME -->
  <div id="superhero-group" class="form-group" ng-class="{ 'has-error' : errorSuperhero }">
   <label>Superhero Alias</label>
   <input type="text" name="superheroAlias" class="form-control" placeholder="Caped Crusader">
   <span class="help-block" ng-show="errorSuperhero">{{ errorSuperhero }}</span>
  </div>
 
...

我們的表單完成了!通過強大的Angular,我們可以將這些愚蠢的顯示/隱藏的js代碼邏輯從視圖中移走 了。現(xiàn)在我們的js文件只用來處理數據,并且視圖可以做它自己的事情了。

我們的類和錯誤/成功等提示信息將在可獲取時顯示而不可獲取時隱藏。當我們無須再像使用老的javascript那樣擔心是否已經考慮全面,這變得更加容易。你也無須再擔心是否記得隱藏每處form提交時的那些錯誤信息。

Angular表單驗證 獲取更多表單驗證的信息,請研讀我們另一文章:AngularJS Form Validation。
結束語

現(xiàn)在我們已把美觀的表單全部轉變?yōu)锳ngular的了。我們共同學習了許多概念,希望你與它們接觸更多,它們也將更易用。

回顧:

  •     創(chuàng)建一個Angular module
  •     創(chuàng)建一個Angular controller
  •     雙向數據綁定
  •     ng-model綁定inputs
  •     ng-click提交表單
  •     使用雙向數據綁定展示表單錯誤
  •     展示一個基于是否變量存在的div
  •     添加一個基于是否變量存在的類

這些Angular技術將在更龐大的應用中使用,你可以用它們創(chuàng)建許多好東西。祝Angular之途愉快,敬請期待更多深入的文章。同時,你也可以通過深入了解其指南,服務和廠商等來繼續(xù)學習Angular。

相關文章

  • Angular搜索場景中使用rxjs的操作符處理思路

    Angular搜索場景中使用rxjs的操作符處理思路

    這篇文章主要介紹了Angular搜索場景中使用rxjs的操作符處理思路,主要的思路就是通過Subject來發(fā)送過濾條件,這樣就可以使用rxjs的各種操作符,可以快捷很多。需要的朋友可以參考下
    2018-05-05
  • AngularJS動態(tài)加載模塊和依賴的方法分析

    AngularJS動態(tài)加載模塊和依賴的方法分析

    這篇文章主要介紹了AngularJS動態(tài)加載模塊和依賴的方法,結合實例形式分析了AngularJS使用ocLazyLoad實現(xiàn)動態(tài)加載的相關操作技巧,需要的朋友可以參考下
    2016-11-11
  • AngularJS自動表單驗證

    AngularJS自動表單驗證

    這篇文章主要介紹了AngularJS手動表單驗證的相關資料,AngularJS的表單驗證大致有兩種,一種是手動驗證,一種是自動驗證,本文重點介紹AngularJS自動表單驗證,感興趣的小伙伴們可以參考一下
    2016-02-02
  • angularjs 頁面自適應高度的方法

    angularjs 頁面自適應高度的方法

    本篇文章主要介紹了angularjs 頁面自適應高度的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-01-01
  • 淺析如何利用angular結合translate為項目實現(xiàn)國際化

    淺析如何利用angular結合translate為項目實現(xiàn)國際化

    利用angular進行國際化轉換時利用【ng-bind-html】來進行語言的翻譯是接近幾乎比較完美的方案,不會像利用【{{}}】模式,當頁面加載緩慢時導致頁面太丑。本文對其實現(xiàn)方法進行介紹,有需要的朋友可以看下
    2016-12-12
  • AngularJS使用angular-formly進行表單驗證

    AngularJS使用angular-formly進行表單驗證

    這篇文章主要介紹了AngularJS使用angular-formly進行表單驗證的相關資料,需要的朋友可以參考下
    2015-12-12
  • 在Angular中實現(xiàn)一個級聯(lián)效果的下拉框的示例代碼

    在Angular中實現(xiàn)一個級聯(lián)效果的下拉框的示例代碼

    這篇文章主要介紹了在Angular中實現(xiàn)一個級聯(lián)效果的下拉框的示例代碼,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2020-05-05
  • 詳解Angular數據綁定及其實現(xiàn)方式

    詳解Angular數據綁定及其實現(xiàn)方式

    數據綁定是將應用程序UI或用戶界面綁定到模型的機制。使用數據綁定,用戶將能夠使用瀏覽器來操縱網站上存在的元素。
    2021-05-05
  • 關于AngularJS中幾種Providers的區(qū)別總結

    關于AngularJS中幾種Providers的區(qū)別總結

    這篇文章主要給大家介紹了關于AngularJS中幾種Providers的區(qū)別的相關資料,文中通過示例代碼介紹的非常詳細,對大家學習或者使用AngularJS具有一定的參考學習價值,需要的朋友們下面來一起學習學習吧
    2020-05-05
  • angular5 httpclient的示例實戰(zhàn)

    angular5 httpclient的示例實戰(zhàn)

    本篇文章主要介紹了angular5 httpclient的示例實戰(zhàn),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-03-03

最新評論

阳曲县| 浪卡子县| 府谷县| 景洪市| 长顺县| 尼玛县| 砚山县| 昭觉县| 西昌市| 垫江县| 洪湖市| 湖州市| 昌图县| 姜堰市| 财经| 临洮县| 加查县| 惠州市| 东阿县| 卢龙县| 贵南县| 新余市| 兴城市| 平武县| 辽阳县| 蒙山县| 孝义市| 林芝县| 乌兰察布市| 吴桥县| 民权县| 奇台县| 闽清县| 新营市| 宁明县| 门源| 南漳县| 台湾省| 郎溪县| 哈巴河县| 芜湖县|