標籤:
1.app.js 配置請求設定
1 $httpProvider.defaults.headers.post={ 2 ‘Content-Type‘:‘application/x-www-form-urlencoded‘} 3 var param = function(obj) { 4 var query = ‘‘, name, value, fullSubName, subName, subValue, innerObj, i; 5 6 for(name in obj) { 7 value = obj[name]; 8 if(value instanceof Array) { 9 for(i=0; i<value.length; ++i) {10 subValue = value[i];11 fullSubName = name + ‘[‘ + i + ‘]‘;12 innerObj = {};13 innerObj[fullSubName] = subValue;14 query += param(innerObj) + ‘&‘;15 }16 }17 else if(value instanceof Object) {18 for(subName in value) {19 subValue = value[subName];20 fullSubName = name + ‘[‘ + subName + ‘]‘;21 innerObj = {};22 innerObj[fullSubName] = subValue;23 query += param(innerObj) + ‘&‘;24 }25 }26 else if(value !== undefined && value !== null)27 query += encodeURIComponent(name) + ‘=‘ + encodeURIComponent(value) + ‘&‘;28 }29 30 return query.length ? query.substr(0, query.length - 1) : query;31 };32 33 // Override $http service‘s default transformRequest34 $httpProvider.defaults.transformRequest = [function(data) {35 return angular.isObject(data) && String(data) !== ‘[object File]‘ ? param(data) : data;36 }];
備忘:這代碼是從網上copy
2.controller.js
1 $scope.openGet=function(){ 2 $http.get("http://192.168.108:8000/ionic.php?uname=su").success( 3 function(response){ 4 console.log("status:"+response.status); 5 alert(response.status); 6 } 7 ).error(function(){ 8 //錯誤訊息 9 });10 }11 $scope.openPost=function(){12 13 $http({14 method: "POST",15 url: "http://192.168.108:8000/ionic.php",16 data: {"id":‘101‘},17 }).success(18 function(response) {19 alert(response.id);20 }21 ).error(function(er) {22 alert(er);23 });24 }
3.html
<button ng-click="openGet()">GET</button><button ng-click="openPost()">POST</button>
4.服務端代碼
1 <?php 2 3 $callback = isset($_GET[‘callback‘]) ? trim($_GET[‘callback‘]) : ‘‘; //jsonp回調參數,必需 4 //採用jsonp 解決跨域問題 方式處理 5 if($callback!=‘‘){ 6 $callback = $_GET[‘callback‘]; 7 $date = array(‘status‘=>‘1‘,‘msg‘=>‘OK‘); 8 echo $callback.‘(‘.json_encode($data).‘)‘; 9 }10 else{11 12 //通過header解決跨域問題13 header(‘Content-Type: application/json‘);14 header("Access-Control-Request-Method: *");15 header(‘Access-Control-Allow-Headers:x-requested-with,content-type‘);16 header("Access-Control-Allow-Origin: *");17 header(‘Access-Control-Max-Age: 60‘);18 19 $uname = isset($_GET[‘uname‘]) ? trim($_GET[‘uname‘]) : ‘‘; 20 21 //echo json_decode($_POST);22 23 $id=isset($_POST[‘id‘])?$_POST[‘id‘]: ‘‘;24 if($uname!=‘‘){25 $date = array(‘uname‘=>$uname);26 $date["msg"]="get OK";27 $date["status"]="1";28 echo json_encode($date); 29 }30 if($id!=‘‘){31 $date = array(‘id‘=>$id);32 $date["msg"]="Post OK";33 $date["status"]="1";34 echo json_encode($date); 35 } 36 //echo json_decode(file_get_contents(‘php://input‘),true);37 }38 39 ?>
備忘:具體原理:http://victorblog.com/2012/12/20/make-angularjs-http-service-behave-like-jquery-ajax/
Ionic 發送Http post PHP 擷取不到資料