| 維度 | jQuery $.ajax | AngularJS $http |
|---|---|---|
| 數據綁定 | 手動序列化 $('#form').serialize() | 自動綁定 ng-model 對象直接傳遞 |
| 錯誤顯示 | 手動操作 DOM 顯示/隱藏 | 雙向綁定自動同步 $error 狀態 |
| 代碼組織 | 分散在回調中 | 控制器集中邏輯,服務層復用 |
| 測試性 | 難以單元測試 | 依賴注入易於 Mock |
<?php
header('Content-Type: application/json; charset=utf-8');
$errors = [];
$data = [];
// 驗證
if (empty($_POST['name'])) $errors['name'] = '姓名不能為空';
if (empty($_POST['superheroAlias'])) $errors['superheroAlias'] = '超級英雄別名不能為空';
// 響應
if (!empty($errors)) {
$data['success'] = false;
$data['errors'] = $errors;
} else {
$data['success'] = true;
$data['message'] = '提交成功!歡迎 ' . htmlspecialchars($_POST['name']);
// 這裡可做入庫、發郵件等業務邏輯
}
echo json_encode($data);
<!DOCTYPE html>
<html ng-app="formApp">
<head>
<meta charset="utf-8">
<title>AngularJS 表單提交演示</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css">
<script src="https://cdn.jsdelivr.net/npm/angular@1.7.9/angular.min.js"></script>
<script src="app.js"></script>
<style>
.has-error .form-control { border-color: #dc3545; }
.help-block { color: #dc3545; margin-top: 5px; }
.alert { margin-top: 15px; }
</style>
</head>
<body ng-controller="FormController">
<div class="container">
<div class="col-md-6 col-md-offset-3">
<div class="page-header"><h1><span class="glyphicon glyphicon-user"></span> 英雄註冊</h1></div>
<!-- 全局消息區域 -->
<div ng-show="resultMessage" class="alert" ng-class="{'alert-success': resultSuccess, 'alert-danger': !resultSuccess}">
{{ resultMessage }}
</div>
<form name="heroForm" ng-submit="submitForm(heroForm.$valid)" novalidate>
<div class="form-group" ng-class="{'has-error': heroForm.name.$invalid && heroForm.name.$dirty}">
<label>姓名</label>
<input type="text" name="name" class="form-control" ng-model="formData.name" required placeholder="Bruce Wayne">
<span class="help-block" ng-show="heroForm.name.$error.required && heroForm.name.$dirty">姓名必填</span>
</div>
<div class="form-group" ng-class="{'has-error': heroForm.superheroAlias.$invalid && heroForm.superheroAlias.$dirty}">
<label>超級英雄別名</label>
<input type="text" name="superheroAlias" class="form-control" ng-model="formData.superheroAlias" required placeholder="Batman">
<span class="help-block" ng-show="heroForm.superheroAlias.$error.required && heroForm.superheroAlias.$dirty">別名必填</span>
</div>
<button type="submit" class="btn btn-success btn-lg btn-block" ng-disabled="heroForm.$invalid || submitting">
<span ng-hide="submitting">提交</span>
<span ng-show="submitting"><span class="glyphicon glyphicon-refresh glyphicon-spin"></span> 提交中...</span>
</button>
</form>
</div>
</div>
</body>
</html>
angular.module('formApp', [])
.controller('FormController', ['$scope', '$http', function($scope, $http) {
$scope.formData = {};
$scope.submitting = false;
$scope.resultMessage = '';
$scope.resultSuccess = false;
$scope.submitForm = function(isValid) {
// 1. 前端二次檢查
if (!isValid) {
// 標記所有字段為 dirty 觸發錯誤顯示
angular.forEach($scope.heroForm.$error, function(fields) {
angular.forEach(fields, function(field) {
field.$setDirty();
});
});
return;
}
// 2. 禁用提交按鈕,防止重複點擊
$scope.submitting = true;
$scope.resultMessage = '';
// 3. $http POST 請求
// 注意:AngularJS 默認發送 application/json,PHP $_POST 讀不到
// 方案 A:後端用 file_get_contents('php://input') + json_decode
// 方案 B:前端轉為 application/x-www-form-urlencoded(推薦兼容性)
$http({
method: 'POST',
url: 'process.php',
data: $.param($scope.formData), // 需引入 jQuery 或自寫序列化
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
})
.then(function(response) {
var data = response.data;
$scope.submitting = false;
if (data.success) {
$scope.resultSuccess = true;
$scope.resultMessage = data.message;
$scope.formData = {}; // 清空表單
$scope.heroForm.$setPristine(); // 重置驗證狀態
$scope.heroForm.$setUntouched();
} else {
$scope.resultSuccess = false;
$scope.resultMessage = '提交失敗:' + (data.errors ? JSON.stringify(data.errors) : '未知錯誤');
// 將後端錯誤映射到前端字段
if (data.errors) {
angular.forEach(data.errors, function(msg, field) {
if ($scope.heroForm[field]) {
$scope.heroForm[field].$setValidity('server', false);
// 自定義錯誤信息需配合 ng-messages 或手動顯示
}
});
}
}
})
.catch(function(response) {
$scope.submitting = false;
$scope.resultSuccess = false;
$scope.resultMessage = '網絡錯誤或服務器異常 (HTTP ' + response.status + ')';
});
};
}]);
AngularJS $http 默認 Content-Type: application/json,PHP $_POST 僅解析 application/x-www-form-urlencoded 和 multipart/form-data。三種解決方案:
data: $.param($scope.formData) + headers: {'Content-Type': 'application/x-www-form-urlencoded'}$input = json_decode(file_get_contents('php://input'), true);$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; $httpProvider.defaults.transformRequest = [$httpParamSerializerJQLike];(需注入 ngMessages 或載入 angular-jquery-param).then(function(response) {
if (!response.data.success && response.data.errors) {
angular.forEach(response.data.errors, function(msg, field) {
var formField = $scope.heroForm[field];
if (formField) {
// 設置服務端驗證錯誤狀態
formField.$setValidity('server', false);
// 存儲錯誤信息供模板顯示
formField.$error.serverMessage = msg;
}
});
}
});
// 模板顯示服務端錯誤
<span class="help-block" ng-show="heroForm.name.$error.server">{{ heroForm.name.$error.serverMessage }}</span>
<input type="file" name="avatar" ng-model="formData.avatar" custom-file-input>
// 指令處理 File 对象
app.directive('customFileInput', function() {
return {
require: 'ngModel',
link: function(scope, elem, attrs, ngModel) {
elem.on('change', function() {
ngModel.$setViewValue(elem[0].files[0]);
});
}
};
});
// 提交時用 FormData
var fd = new FormData();
fd.append('avatar', $scope.formData.avatar);
angular.forEach($scope.formData, function(v, k) { if (k !== 'avatar') fd.append(k, v); });
$http.post('upload.php', fd, {
transformRequest: angular.identity,
headers: { 'Content-Type': undefined } // 瀏覽器自動設置 multipart/form-data boundary
});
ng-disabled="submitting" + 服務端冪等性 Tokenng-show="form.field.$error.xxx && form.field.$dirty"$setPristine() + $setUntouched() + 清空模型type="submit" 按鈕、合理的 tabindexAngularJS 表單提交的核心優勢在於雙向數據綁定自動收集數據、內置驗證狀態機、$http 服務統一異步處理。配合後端標準化 JSON 響應格式({success, message, errors}),可構建健壯、用戶友好、易維護的表單交互系統。關鍵記住:前端驗證為體驗,後端驗證為安全,雙重保障缺一不可。