1. 程式人生 > >php+Angularjs 實現Post 提交表單 模擬登入

php+Angularjs 實現Post 提交表單 模擬登入

1、在開始之前我們要了解下angularjs的$http函式,post請求可以簡寫成$http.post 同時也可以像jQuery那樣$http(method:'',url:'',params:'')。
2、在開始之前我們要先宣告下預設的http頭資訊
$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
不寫的話可能會在後臺接受不到
3、程式碼如下
前臺程式碼:
<html  ng-app="myApp"  ng-controller="customersCtrl">
<
head><script src="http://code.angularjs.org/angular-1.0.1.min.js"></script></head> <body> <div > <form> <input type="text" ng-model="user.name" value="123"> <input type="password" ng-model="user.password" value="123"> {{showinfo}} <input
type="button" ng-click="myform1()" value="登入"> </form> </div> <script> console.log(app); // var firstname={firstName} // alert(); var app = angular.module('myApp', []); app.controller('customersCtrl', function ($scope, $http) { $http.defaults.headers
.post["Content-Type"] = "application/x-www-form-urlencoded"; $scope.user = {"name": "11231", "password": "111"}; $scope.showinfo=""; console.log($scope.user); $scope.myform1 = function () { $http({ method: 'post', url: 'aaa.php', params: $scope.user }).success(function (data1) { console.log(data1.result); if(data1.result=="ok"){ $scope.showinfo="登入成功"; $scope.user = {"name": "", "password": ""}; }else { $scope.showinfo="登入失敗,請核對使用者名稱密碼"; } } ); } }); </script> </body> </html>
php程式碼:
<?php
if(isset($_GET["name"])&&isset($_GET["password"])){
$username=$_GET["name"];
$password=$_GET["password"];
if($username==1&&$password==1){
echo json_encode(array('status'=>0,'result'=>'ok'));
    }else{
echo json_encode(array('status'=>'0','result'=>'error'));
    }
}