在AngularJS出现之前,很多开发者就面对了表单提交这一问题。由于提交表单的方式繁杂而不同,很容易令人疯掉……然而现在看来,依然会让人疯掉。
今天,我们会看一下过去使用PHP方式提交的表单,现在如何将其转换为使用Angular提交。使用Angular来处理表单,对我而言,是一个“啊哈”时刻(译者:表示了解或发现某事物的喜悦)。即使它甚至都没有涉及多少Angular表层的东西,但是它却帮助用户看到表单提交之后的潜力,并且理解两种数据绑定方式。
我们会使用jQuery平台来进行这个处理过程。所以所要做的工作首先使用javascript。我们会提交表单,展示错误信息,添加错误类,并且在javascript中显示和隐藏信息。
之后,我们会使用Angular。在使用之前,我们要做大部分所需的工作,并且我们之前所做的很多工作会非常容易。让我们开始吧。
简单的表单
我们会关注两种提交表单的方式:
- 旧方法:jQuery和PHP提交表单
- 新方法:AngularJS和PHP提交表单
首先看一下我们的表单,超级简单:
形式要求
- 实现页面无刷新表单处理
- 输入姓名和超级英雄别名
- 如果有错误,显示错误提示
- 如果输入有误,将输入变成红色
- 如果所有内容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);</div> 这是一个非常简单的表单处理脚本。我们仅检查数据是否存在,如果存在,则不做任何处理和操做;如果不存在,则需要向$errors数组中添加一条信息。</div>
为了返回我们的数据用于AJAX调用,我们需要使用echo和json_encode。这就是我们PHP表单处理所有需要做的操作。使用普通的jQuery AJAX或者Angular处理表单也是这样的。
展示表单
让我们创建一个HTML来展示我们的表单
<!-- index.html --> <!doctype html> <html> <head> <title>Angular Forms</title> <!-- LOAD BOOTSTRAP CSS --> <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.2/css/bootstrap.min.css"> <!-- 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="//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></div>
现在,我们有了表单。我们另外还使用了Bootstrap来使表单看起来不是那么丑。使用Bootstrap语法规则,每个input下含有一个spot来展示我们文本的错误信息。
使用jQuery提交表单
现在,让我们来使用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> ...</div>
这里处理表单有不少的代码。我们有获取表单中变量的代码,有使用AJAX将数据发送至我们的表单的代码,有检查是否有错和显示成功提示的代码。除此之外,我们希望每次表单