Angular學(xué)習(xí)筆記之ng表單驗(yàn)證

本人即將大四,小白一個(gè),這是第一次在學(xué)習(xí)論壇上寫點(diǎn)東西,因?yàn)橄腽B(yǎng)成一個(gè)隨時(shí)記錄自己學(xué)習(xí)進(jìn)程的好習(xí)慣。因?yàn)楣纠锸褂玫氖茿ngular,so斷斷續(xù)續(xù)學(xué)習(xí)了半個(gè)月左右,現(xiàn)在到了檢驗(yàn)的時(shí)候。

一些Angular基礎(chǔ)的標(biāo)簽我就不說(shuō)了,先從我比較感興趣也是比較簡(jiǎn)單的表單驗(yàn)證開始入門吧。

(大神就還是不要往下看啦0.0)


首先,構(gòu)建的表單幾點(diǎn)要求:

1.確保form上標(biāo)簽有一個(gè)name屬性,像下面的例子一樣。最好再加一個(gè)novalidate=”novalidate”,此屬性是為了驗(yàn)證表單時(shí)禁止使用表單自身的驗(yàn)證方法;

2.form中不能有action屬性,提交交由ng-submit處理(我這里好像是直接改成了ng-click);

3.每個(gè)input一定要有ng-model,最好有一個(gè)name方便引用。然后用require或者ng-minlength之類才起作用;

4.novalidate="novalidate",關(guān)閉原有的html5表單驗(yàn)證;


先上幾張截圖:


登錄界面

登錄界面的驗(yàn)證有:所有字段的空驗(yàn)證,合法性驗(yàn)證,位數(shù)驗(yàn)證等;用戶名和密碼在angular控制器中與后臺(tái)數(shù)據(jù)庫(kù)交互,簡(jiǎn)單的判斷是否存在該用戶;

注冊(cè)界面

注冊(cè)界面驗(yàn)證:所有字段的空驗(yàn)證,合法性驗(yàn)證,位數(shù)驗(yàn)證等;用戶名在controller中驗(yàn)證是否數(shù)據(jù)庫(kù)中存在相同的用戶名;兩次密碼的輸入是否一致等;

因?yàn)槭呛芎?jiǎn)單的練手demo,代碼也就沒(méi)那么規(guī)范啦:)


代碼區(qū)

test19.html ? ? ? ?//登錄界面

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>angular驗(yàn)證 ?前臺(tái)登錄頁(yè)面</title>

<script src="https://cdn.bootcss.com/jquery/2.1.1/jquery.min.js"></script>

<link rel="stylesheet">

<script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script>

</head>

<body>

<div class="container" style="width: 600px;border: 1px solid #cccccc;box-shadow: 0 0 10px 3px #cccccc;margin-top: 150px;">

<form class="form-horizontal" name="form" ng-app="myApp" ng-controller="myCtrl" ng-submit="submitForm(form.$valid)" novalidate="novalidate">

<h2 class="col-sm-offset-2 col-sm-10">表單驗(yàn)證</h2>

<div class="form-group has-feedback" ng-class="{ 'has-error' : form.user.$invalid && form.user.$dirty || userValidate=='false' , 'has-success' : form.user.$valid && form.user.$dirty && (userValidate=='' || userValidate=='true') }">

<label for="user" class="col-sm-2 control-label">用戶名:</label>

<div class="col-sm-5">

<input type="text" class="form-control" name="user" id="user" ng-model="user" ng-minlength="3" ng-maxlength="8" required="required" />

<span class="glyphicon glyphicon-ok form-control-feedback" ng-show="form.user.$dirty && form.user.$valid && (userValidate=='' || userValidate=='true')" aria-hidden="true"></span>

<span class="glyphicon glyphicon-remove form-control-feedback" ng-show="form.user.$dirty && form.user.$invalid || userValidate=='false'" aria-hidden="true"></span>

</div>

<span class="col-sm-5" ng-show="form.user.$dirty && form.user.$invalid">

<span class="help-block" ng-show="form.user.$error.required">用戶名是必須的</span>

<span class="help-block" ng-show="form.user.$error.minlength">your name is too short!</span>

<span class="help-block" ng-show="form.user.$error.maxlength">your name is too long!</span>

</span>

<span class="col-sm-5" ng-show="form.user.$dirty && form.user.$valid">

<span class="help-block" ng-show="form.user.$valid && userValidate!='false'">OK</span>

<span class="help-block" ng-show="userValidate=='false'">用戶名或密碼錯(cuò)誤</span>

</span>

</div>

<div class="form-group has-feedback" ng-class="{ 'has-error' : form.email.$invalid && form.email.$dirty , 'has-success' : form.email.$valid && form.email.$dirty }">

<label for="email" class="col-sm-2 control-label">郵箱:</label>

<div class="col-sm-5">

<input type="email" class="form-control" name="email" id="email" ng-model="email" required="required" />

<span class="glyphicon glyphicon-ok form-control-feedback" ng-show="form.email.$dirty && form.email.$valid" aria-hidden="true"></span>

<span class="glyphicon glyphicon-remove form-control-feedback" ng-show="form.email.$dirty && form.email.$invalid" aria-hidden="true"></span>

</div>

<span class="col-sm-5" ng-show="form.email.$dirty && form.email.$invalid">

<span class="help-block" ng-show="form.email.$error.required">郵箱是必須的</span>

<span class="help-block" ng-show="form.email.$error.email">郵箱地址非法</span>

</span>

<span class="col-sm-5" ng-show="form.email.$dirty && form.email.$valid">

<span class="help-block" ng-show="form.email.$valid">OK</span>

</span>

</div>

<div class="form-group has-feedback" ng-class="{ 'has-error' : form.phone.$invalid && form.phone.$dirty , 'has-success' : form.phone.$valid && form.phone.$dirty }">

<label for="phone" class="col-sm-2 control-label">手機(jī)號(hào):</label>

<div class="col-sm-5">

<input type="tel" class="form-control" name="phone" id="phone" ng-pattern="regex" ng-model="phone" required="required" />

<span class="glyphicon glyphicon-ok form-control-feedback" ng-show="form.phone.$dirty && form.phone.$valid" aria-hidden="true"></span>

<span class="glyphicon glyphicon-remove form-control-feedback" ng-show="form.phone.$dirty && form.phone.$invalid" aria-hidden="true"></span>

</div>

<span class="col-sm-5" ng-show="form.phone.$dirty && form.phone.$invalid">

<span class="help-block" ng-show="form.phone.$error.required">手機(jī)號(hào)不能為空</span>

<span class="help-block" ng-show="form.phone.$error.pattern">請(qǐng)輸入正確的11位手機(jī)號(hào)碼</span>

</span>

<span class="col-sm-5" ng-show="form.phone.$dirty && form.phone.$valid">

<span class="help-block" ng-show="form.phone.$valid">OK</span>

</span>

</div>


<div class="form-group has-feedback" ng-class="{ 'has-error' : form.password.$invalid && form.password.$dirty || userValidate=='false' , 'has-success' : form.password.$valid && form.password.$dirty && (userValidate=='' || userValidate=='true') }">

<label for="password" class="col-sm-2 control-label">密碼:</label>

<div class="col-sm-5">

<input type="password" class="form-control" name="password" id="password" ng-pattern="" ng-model="password" required="required" />

<span class="glyphicon glyphicon-ok form-control-feedback" ng-show="form.password.$dirty && form.password.$valid && (userValidate=='' || userValidate=='true')" aria-hidden="true"></span>

<span class="glyphicon glyphicon-remove form-control-feedback" ng-show="form.password.$dirty && form.password.$invalid || userValidate=='false'" aria-hidden="true"></span>

</div>

<span class="col-sm-5" ng-show="form.password.$dirty && form.password.$invalid">

<span class="help-block" ng-show="form.password.$error.required">密碼不能為空</span>

<!--<span class="help-block" ng-show="form.password.$error.pattern">請(qǐng)輸入正確的密碼</span>-->

</span>

<span class="col-sm-5" ng-show="form.password.$dirty && form.password.$valid">

<span class="help-block" ng-show="form.password.$valid && userValidate!='false'">OK</span>

</span>

</div>

<div class="form-group">

<div class="col-sm-offset-2 col-sm-10">

<input type="submit" class="btn btn-primary" ng-click="validate()" value="submit" ng-disabled="form.user.$dirty && form.user.$invalid || form.email.$dirty && form.email.$invalid || form.phone.$dirty && form.phone.$invalid" />

<a href="test19_register.html" class="btn btn-warning" ng-click="register()">register</a>

</div>

</div>

<!--<span>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>-->

</form>

</div>


<script type="text/javascript">

//要像這樣加載模板和控制器驗(yàn)證才能有效

var app = angular.module('myApp', []);


app.config(function($httpProvider){

$httpProvider.defaults.transformRequest = function(obj){

var str = [];

for(var p in obj){

str.push(encodeURIComponent(p)+"="+encodeURIComponent(obj[p]));

}

return str.join("&");

}

$httpProvider.defaults.headers.post = {

'Content-Type' : 'application/x-www-form-urlencoded'

}

});


app.controller('myCtrl', function($scope,$http) {

$scope.regex = /^1[34578]\d{9}$/;

$scope.userValidate = '';


//驗(yàn)證用戶名

$scope.validate = function(){

$http

.post('http://localhost/test19_validate.php',{name : $scope.user, email : $scope.email, tel : $scope.phone, password : $scope.password})

.then(function successCallback(response){

//用戶名或密碼錯(cuò)誤

if(response.data == 'error'){

$scope.userValidate = 'false';

}else{

$scope.userValidate = 'true';

window.location = './test19_success.html';

}

},function errorCallback(response){

alert('驗(yàn)證失敗');

});

}


});

</script>

</body>

</html>

test19_register.html ? ? ? ?//用戶注冊(cè)頁(yè)面

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>test19_用戶注冊(cè)頁(yè)面</title>

<script src="https://cdn.bootcss.com/jquery/2.1.1/jquery.min.js"></script>

<link rel="stylesheet">

<script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script>

</head>

<body>

<div class="container" style="width: 600px;border: 1px solid #cccccc;box-shadow: 0 0 10px 3px #cccccc;margin-top: 150px;">

<form class="form-horizontal" name="form" ng-app="myApp" ng-controller="myCtrl" ng-submit="submitForm(form.$valid)" novalidate="novalidate">

<h2 class="col-sm-offset-2 col-sm-10">表單驗(yàn)證</h2>

<div class="form-group has-feedback" ng-class="{ 'has-error' : form.user.$invalid && form.user.$dirty || rename , 'has-success' : form.user.$valid && form.user.$dirty && !rename }">

<label for="user" class="col-sm-2 control-label">用戶名:</label>

<div class="col-sm-5">

<input type="text" class="form-control" name="user" id="user" ng-model="user" ng-minlength="3" ng-maxlength="8" required="required" />

<span class="glyphicon glyphicon-ok form-control-feedback" ng-show="form.user.$dirty && form.user.$valid && !rename" aria-hidden="true"></span>

<span class="glyphicon glyphicon-remove form-control-feedback" ng-show="form.user.$dirty && form.user.$invalid || rename" aria-hidden="true"></span>

</div>

<span class="col-sm-5" ng-show="form.user.$dirty && form.user.$invalid || rename">

<span class="help-block" ng-show="form.user.$error.required">用戶名是必須的</span>

<span class="help-block" ng-show="form.user.$error.minlength">your name is too short!</span>

<span class="help-block" ng-show="form.user.$error.maxlength">your name is too long!</span>

<span class="help-block" ng-show="rename">用戶名已存在</span>

</span>

<span class="col-sm-5" ng-show="form.user.$dirty && form.user.$valid">

<span class="help-block" ng-show="form.user.$valid && !rename">OK</span>

</span>

</div>

<div class="form-group has-feedback" ng-class="{ 'has-error' : form.email.$invalid && form.email.$dirty , 'has-success' : form.email.$valid && form.email.$dirty }">

<label for="email" class="col-sm-2 control-label">郵箱:</label>

<div class="col-sm-5">

<input type="email" class="form-control" name="email" id="email" ng-model="email" required="required" />

<span class="glyphicon glyphicon-ok form-control-feedback" ng-show="form.email.$dirty && form.email.$valid" aria-hidden="true"></span>

<span class="glyphicon glyphicon-remove form-control-feedback" ng-show="form.email.$dirty && form.email.$invalid" aria-hidden="true"></span>

</div>

<span class="col-sm-5" ng-show="form.email.$dirty && form.email.$invalid">

<span class="help-block" ng-show="form.email.$error.required">郵箱是必須的</span>

<span class="help-block" ng-show="form.email.$error.email">郵箱地址非法</span>

</span>

<span class="col-sm-5" ng-show="form.email.$dirty && form.email.$valid">

<span class="help-block" ng-show="form.email.$valid">OK</span>

</span>

</div>

<div class="form-group has-feedback" ng-class="{ 'has-error' : form.phone.$invalid && form.phone.$dirty , 'has-success' : form.phone.$valid && form.phone.$dirty }">

<label for="phone" class="col-sm-2 control-label">手機(jī)號(hào):</label>

<div class="col-sm-5">

<input type="tel" class="form-control" name="phone" id="phone" ng-pattern="regex" ng-model="phone" required="required" />

<span class="glyphicon glyphicon-ok form-control-feedback" ng-show="form.phone.$dirty && form.phone.$valid" aria-hidden="true"></span>

<span class="glyphicon glyphicon-remove form-control-feedback" ng-show="form.phone.$dirty && form.phone.$invalid" aria-hidden="true"></span>

</div>

<span class="col-sm-5" ng-show="form.phone.$dirty && form.phone.$invalid">

<span class="help-block" ng-show="form.phone.$error.required">手機(jī)號(hào)不能為空</span>

<span class="help-block" ng-show="form.phone.$error.pattern">請(qǐng)輸入正確的11位手機(jī)號(hào)碼</span>

</span>

<span class="col-sm-5" ng-show="form.phone.$dirty && form.phone.$valid">

<span class="help-block" ng-show="form.phone.$valid">OK</span>

</span>

</div>

<div class="form-group has-feedback" ng-class="{ 'has-error' : form.password.$invalid && form.password.$dirty , 'has-success' : form.password.$valid && form.password.$dirty }">

<label for="password" class="col-sm-2 control-label">密碼:</label>

<div class="col-sm-5">

<input type="password" class="form-control" name="password" id="password" ng-pattern="" ng-model="password" required="required" />

<span class="glyphicon glyphicon-ok form-control-feedback" ng-show="form.password.$dirty && form.password.$valid" aria-hidden="true"></span>

<span class="glyphicon glyphicon-remove form-control-feedback" ng-show="form.password.$dirty && form.password.$invalid" aria-hidden="true"></span>

</div>

<span class="col-sm-5" ng-show="form.password.$dirty && form.password.$invalid">

<span class="help-block" ng-show="form.password.$error.required">密碼不能為空</span>

<!--<span class="help-block" ng-show="form.password.$error.pattern">請(qǐng)輸入正確的密碼</span>-->

</span>

<span class="col-sm-5" ng-show="form.password.$dirty && form.password.$valid">

<span class="help-block" ng-show="form.password.$valid">OK</span>

</span>

</div>


<div class="form-group has-feedback" ng-class="{ 'has-error' : form.confirmPassword.$invalid && form.confirmPassword.$dirty || (password!=confirmPassword && form.confirmPassword.$dirty) , 'has-success' : form.confirmPassword.$valid && form.confirmPassword.$dirty && password==confirmPassword }">

<label for="confirmPassword" class="col-sm-2 control-label">確認(rèn)密碼:</label>

<div class="col-sm-5">

<input type="password" class="form-control" name="confirmPassword" id="confirmPassword" ng-pattern="" ng-model="confirmPassword" required="required" />

<span class="glyphicon glyphicon-ok form-control-feedback" ng-show="form.confirmPassword.$dirty && form.confirmPassword.$valid && password==confirmPassword" aria-hidden="true"></span>

<span class="glyphicon glyphicon-remove form-control-feedback" ng-show="form.confirmPassword.$dirty && form.confirmPassword.$invalid || (password!=confirmPassword && form.confirmPassword.$dirty)" aria-hidden="true"></span>

</div>

<span class="col-sm-5" ng-show="form.confirmPassword.$dirty && form.confirmPassword.$invalid">

<span class="help-block" ng-show="form.confirmPassword.$error.required">密碼不能為空</span>

</span>

<span class="col-sm-5" ng-show="form.confirmPassword.$dirty && form.confirmPassword.$valid">

<span class="help-block" ng-show="form.confirmPassword.$valid && password==confirmPassword">OK</span>

<span class="help-block" ng-show="password!=confirmPassword && form.confirmPassword.$dirty">兩次密碼不一致</span>

</span>

</div>

<div class="form-group">

<div class="col-sm-offset-2 col-sm-10">

<input type="submit" class="btn btn-primary" value="submit" ng-disabled="form.user.$dirty && form.user.$invalid || form.email.$dirty && form.email.$invalid || form.phone.$dirty && form.phone.$invalid || form.password.$dirty && form.password.$invalid || form.confirmPassword.$dirty && form.confirmPassword.$invalid || confirmPassword!=password" />

</div>

</div>

<!--<span>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>-->

</form>

</div>


<script type="text/javascript">

//要像這樣加載模板和控制器驗(yàn)證才能有效

var app = angular.module('myApp', []);


app.config(function($httpProvider){

$httpProvider.defaults.transformRequest = function(obj){

var str = [];

for(var p in obj){

str.push(encodeURIComponent(p)+"="+encodeURIComponent(obj[p]));

}

return str.join("&");

}

$httpProvider.defaults.headers.post = {

'Content-Type' : 'application/x-www-form-urlencoded'

}

});


app.controller('myCtrl', function($scope , $http) {

$scope.regex = /^1[34578]\d{9}$/;

$scope.rename = false;


//表單提交

$scope.submitForm = function(isValid) {

if(isValid) {

$http

.post('http://localhost/test19_register.php?m=add',{name : $scope.user, email : $scope.email, tel : $scope.phone, password : $scope.password})

.then(function successCallback(response){

if(response.data == '此用戶名已被注冊(cè)'){

//用戶名已存在

$scope.rename = true;

}else{

//注冊(cè)成功

alert(response.data);

window.location = './test19.html';

}

},function errorCallback(response){

alert(response.data);

});

}

}


});

</script>

</body>

</html>


test19_validate.php

<?php

? ? /*一定要加上這兩個(gè)header*/

? ? header("Access-Control-Allow-Origin: *");

? ? header("Content-Type: application/json; charset=UTF-8");

? ? header("Content-Type:text/html;charset=utf-8");

? ? $connect = mysqli_connect('localhost','root','root','angular') or die('Unale to connect');

? ? //用戶登錄驗(yàn)證

? ? $post = [];

? ? $formData = [];

? ? $data = file_get_contents("php://input");

? ? $data = explode('&',$data);

? ? foreach ($data as $k => $v){

? ? ? ? $post[] = explode('=',$v);

? ? }

? ? foreach ($post as $k => $v){

? ? ? ? $formData += [$v[0] => urldecode($v[1])];

? ? }

? ? $name = $formData['name'];

? ? $email = $formData['email'];

? ? $tel = $formData['tel'];

? ? $password = $formData['password'];

? ? $password = md5($password);

? ? $sql = "SELECT * FROM user WHERE name='$name' AND password='$password'";

? ? $result = mysqli_query($connect,$sql);

? ? $row = mysqli_fetch_assoc($result);

? ? if($row){

? ? ? ? echo 'success';

? ? }else{

? ? ? ? echo 'error';

? ? }

?>

test19_register.php

<?php

? ? /*一定要加上這兩個(gè)header*/

? ? header("Access-Control-Allow-Origin: *");

? ? header("Content-Type: application/json; charset=UTF-8");

? ? header("Content-Type:text/html;charset=utf-8");

? ? $connect = mysqli_connect('localhost','root','root','angular') or die('Unale to connect');

? ? //用戶注冊(cè)

? ? if($_GET['m'] == 'add'){

? ? ? ? $post = [];

? ? ? ? $formData = [];

? ? ? ? $data = file_get_contents("php://input");

? ? ? ? $data = explode('&',$data);

? ? ? ? foreach ($data as $k => $v){

? ? ? ? ? ? $post[] = explode('=',$v);

? ? ? ? }

? ? ? ? foreach ($post as $k => $v){

? ? ? ? ? ? $formData += [$v[0] => urldecode($v[1])];

? ? ? ? }

? ? ? ? $name = $formData['name'];

? ? ? ? //不能有相同的用戶名

? ? ? ? $sql = "SELECT * FROM user WHERE name='$name'";

? ? ? ? $result = mysqli_query($connect,$sql);

? ? ? ? //$row為找到的滿足條件的一條條記錄

? ? ? ? $row = mysqli_fetch_assoc($result);

? ? ? ? if($row){

? ? ? ? ? ? //若有相同的用戶名已注冊(cè)

? ? ? ? ? ? echo '此用戶名已被注冊(cè)';

? ? ? ? ? ? die;

? ? ? ? }

? ? ? ? $email = $formData['email'];

? ? ? ? $tel = $formData['tel'];

? ? ? ? $password = $formData['password'];

? ? ? ? $password = md5($password);

? ? ? ? $sql = "INSERT INTO user(name,email,tel,password) VALUES ('$name', '$email', '$tel', '$password')";

? ? ? ? $result = mysqli_query($connect,$sql);

? ? ? ? if($result){

? ? ? ? ? ? echo '用戶注冊(cè)成功,請(qǐng)重新登錄';

? ? ? ? }else{

? ? ? ? ? ? echo '注冊(cè)失敗';

? ? ? ? }

? ? }

?>

(寫這兩個(gè)php文件的時(shí)候偷了下懶,只是粗略的實(shí)現(xiàn)了自己想要的功能)


其中驗(yàn)證部分,因?yàn)槭褂玫氖荁ootStrap,配合Angular實(shí)現(xiàn)的效果個(gè)人還是蠻喜歡的,驗(yàn)證除了要寫的正則表達(dá)式外(好像還沒(méi)有加上...),在控制器中基本上是沒(méi)有代碼的;這里補(bǔ)充幾個(gè)Angular中表單的狀態(tài):

$dirty ? ?表單有填寫記錄

$valid ? ?字段內(nèi)容合法的

$invalid ? ?字段內(nèi)容是非法的

$pristine ? ?表單沒(méi)有填寫記錄

$error ? ?包含該驗(yàn)證字段的錯(cuò)誤信息,像 required,minlength,maxlength等等;

其實(shí)寫這個(gè)用戶登錄注冊(cè),主要是想熟悉了解Angular中對(duì)數(shù)據(jù)庫(kù)的操作,$http;

(以下是個(gè)人對(duì)Angular操作數(shù)據(jù)庫(kù)的理解,肯定是還有很多問(wèn)題的,望大牛們多多指點(diǎn)0.0)

var app = angular.module('myApp', []); ? ?//定義應(yīng)用類

app.controller('myCtrl', function($scope,$http) {}); ? ?//定義控制器

(若要使用$http這個(gè)服務(wù),記得一定要事先引用它哦)

要解釋$http服務(wù)前,我想先談?wù)勎覍?duì)$scope的理解:

$scope是一個(gè)把view(一個(gè)DOM元素)連結(jié)到controller上的對(duì)象, $scope 實(shí)際上就是一個(gè)JavaScript對(duì)象; 每一個(gè)Angular應(yīng)用都會(huì)有一個(gè) $rootScope。這個(gè) $rootScope 是最頂級(jí)的scope,它對(duì)應(yīng)著含有 ng-app 指令屬性的那個(gè)DOM元素。 要明確創(chuàng)建一個(gè)$scope 對(duì)象,我們就要給DOM元素安上一個(gè)controller對(duì)象,使用的是ng-controller 指令屬性; ng-model指令屬性 被用來(lái)將DOM文本輸入框的值,跟controller里的$scope model綁定起來(lái)。具體的實(shí)現(xiàn)過(guò)程,是在這個(gè)值上綁定了一個(gè)$watch函數(shù)(類似JavaScript里的事件監(jiān)聽函數(shù))。

接下來(lái)是$http

操作數(shù)據(jù)庫(kù)之前,通常需要在前端和數(shù)據(jù)庫(kù)之間編寫一層“Web服務(wù)”。 AngularJS應(yīng)用程序會(huì)向你的Web服務(wù)發(fā)出請(qǐng)求。 你的Web服務(wù)將與MySQL進(jìn)行通信,以檢查用戶權(quán)限,讀取數(shù)據(jù)或?qū)懭霐?shù)據(jù)。這些后端Web服務(wù)可以用任何語(yǔ)言和框架來(lái)編寫。

首先,$http中有兩個(gè)常用的請(qǐng)求get和post方法;分別有兩個(gè)寫法:

1.$http.get('test.php',{});

2.$http({

? ? ?method : 'get',

? ? ?url : 'test.php',

? ? ?params : {

? ? ? ? ? 'username' : 'lzc'

? ? ?}

});

由于增刪改都需要由html頁(yè)面?zhèn)鬟f數(shù)據(jù)到后臺(tái)php文件中,但是像$http.post('test.php' , {id : 1});這樣傳遞,在php文件中用$_POST是獲取不到傳遞過(guò)來(lái)的數(shù)據(jù)的。So...

angular中$http模塊POST請(qǐng)求request pay load轉(zhuǎn)form data的兩種方法:

? ? ? ? ? ? ? ?var app = angular.module('app',[]);

? ? ? ? ? ? ? ? //angular中$http模塊POST請(qǐng)求request pay load轉(zhuǎn)form data的兩種方法

? ? ? ? ? ? ? ? //打開瀏覽器的調(diào)試工具,會(huì)在Network中看到這些信息

? ? ? ? ? ? ? ? //方法一

? ? ? ? ? ? ? ? app.config(function($httpProvider){

? ? ? ? ? ? ? ? ? ? ?$httpProvider.defaults.transformRequest = function(obj){

? ? ? ? ? ? ? ? ? ? ? ? ? ?var str = [];

? ? ? ? ? ? ? ? ? ? ? ? ? ?for(var p in obj){

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? str.push(encodeURIComponent(p)+"="+encodeURIComponent(obj[p]));

? ? ? ? ? ? ? ? ? ? ? ? ? ?}

? ? ? ? ? ? ? ? ? ? ? ? ? ?return str.join("&");

? ? ? ? ? ? ? ? ? ? ?}

? ? ? ? ? ? ? ? ? ? ?$httpProvider.defaults.headers.post = {

? ? ? ? ? ? ? ? ? ? ? ? ? ?'Content-Type' : 'application/x-www-form-urlencoded'

? ? ? ? ? ? ? ? ? ? ?}

? ? ? ? ? ? ? ? });

? ? ? ? ? ? ? ? //方法二

? ? ? ? ? ? ? ? app.controller('ctrl',function($scope,$http){

? ? ? ? ? ? ? ? ? ? ?$http({

? ? ? ? ? ? ? ? ? ? ? ? ? ?method : 'post',

? ? ? ? ? ? ? ? ? ? ? ? ? ?url : 'http://localhost/test20.php',

? ? ? ? ? ? ? ? ? ? ? ? ? ?data : {name : 'lzc' , age : 20},

? ? ? ? ? ? ? ? ? ? ? ? ? ?headers : {'Content-Type':'application/x-www-form-urlencoded'},

? ? ? ? ? ? ? ? ? ? ? ? ? ?transformRequest:function(obj){

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? var str = [];

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? for(var p in obj){

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?str.push(encodeURIComponent(p)+"="+encodeURIComponent(obj[p]));

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? }

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? return str.join("&");

? ? ? ? ? ? ? ? ? ? ? ? ? ?}

? ? ? ? ? ? ? ? ? ? ?}).then(function successCallback(response){

? ? ? ? ? ? ? ? ? ? ? ? ? ?alert('s');

? ? ? ? ? ? ? ? ? ? ?},function errorCallback(response){

? ? ? ? ? ? ? ? ? ? ? ? ? ?alert('er');

? ? ? ? ? ? ? ? ? ? ?});

? ? ? ? ? ? ? ? });

php文件:

<?php

? ? /*一定要加上這兩個(gè)header*/

? ? header("Access-Control-Allow-Origin: *");

// ? ?header("Content-Type: application/json; charset=UTF-8");

? ? header("Content-Type:text/html;charset=utf-8");


? ? $post = [];

? ? $formData = [];

? ? $data = file_get_contents("php://input");

? ? $data = explode('&',$data);

? ? foreach ($data as $k => $v){

? ? ? ? $post[] = explode('=',$v);

? ? }

? ? foreach ($post as $k => $v){

? ? ? ? $formData += [$v[0] => urldecode($v[1])];

? ? }


? ? $name = $formData['name'];

? ? $quantity = $formData['quantity'];

? ? $price = $formData['price'];


? ? $connect = mysqli_connect('localhost','root','root','angular') or die('Unale to connect');

? ? $sql = "insert into shop (name,quantity,price) values('$name','$quantity','$price')";

? ? $result = mysqli_query($connect,$sql);

? ? if($result){

? ? ? ? echo 'success';

? ? }else{

? ? ? ? echo 'error';

? ? }

?>

至此總得就寫完啦,第一次肯定會(huì)有很多問(wèn)題,歡迎大家指出不足的問(wèn)題。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,616評(píng)論 19 139
  • 通過(guò)AngularJS仿豆瓣一刻的案例:https://github.com/zhongxiaolian/doub...
    中小戀閱讀 1,888評(píng)論 1 21
  • 自己做dede的開發(fā)時(shí)間也比較長(zhǎng)了,基本上常用的函數(shù)都知道在哪個(gè)文件里面,但是時(shí)間一長(zhǎng),也有點(diǎn)模糊了,俗話說(shuō):好記...
    大劉的英語(yǔ)世界閱讀 1,909評(píng)論 1 9
  • AngularJS是什么?AngularJs(后面就簡(jiǎn)稱ng了)是一個(gè)用于設(shè)計(jì)動(dòng)態(tài)web應(yīng)用的結(jié)構(gòu)框架。首先,它是...
    200813閱讀 1,788評(píng)論 0 3
  • Angular面試題 一、ng-show/ng-hide與ng-if的區(qū)別? 第一點(diǎn)區(qū)別是,ng-if在后面表達(dá)式...
    w_zhuan閱讀 5,708評(píng)論 0 26

友情鏈接更多精彩內(nèi)容