您的位置:首页 > 理论基础 > 计算机网络

Ionic 发送Http post PHP 获取不到数据

2016-08-09 20:40 951 查看
1.app.js 配置请求设置

$httpProvider.defaults.headers.post={
'Content-Type':'application/x-www-form-urlencoded'}
var param = function(obj) {
var query = '', name, value, fullSubName, subName, subValue, innerObj, i;

for(name in obj) {
value = obj[name];
if(value instanceof Array) {
for(i=0; i<value.length; ++i) {
subValue = value[i];
fullSubName = name + '[' + i + ']';
innerObj = {};
innerObj[fullSubName] = subValue;
query += param(innerObj) + '&';
}
}
else if(value instanceof Object) {
for(subName in value) {
subValue = value[subName];
fullSubName = name + '[' + subName + ']';
innerObj = {};
innerObj[fullSubName] = subValue;
query += param(innerObj) + '&';
}
}
else if(value !== undefined && value !== null)
query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';
}

return query.length ? query.substr(0, query.length - 1) : query;
};

// Override $http service's default transformRequest
$httpProvider.defaults.transformRequest = [function(data) {
return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data;
}];


备注:这代码是从网上copy

2.controller.js

$scope.openGet=function(){
$http.get("http://192.168.108:8000/ionic.php?uname=su").success(
function(response){
console.log("status:"+response.status);
alert(response.status);
}
).error(function(){
//错误消息
});
}
$scope.openPost=function(){

$http({
method: "POST",
url: "http://192.168.108:8000/ionic.php",
data: {"id":'101'},
}).success(
function(response) {
alert(response.id);
}
).error(function(er) {
alert(er);
});
}


3.html

<button  ng-click="openGet()">GET</button>
<button  ng-click="openPost()">POST</button>


4.服务端代码

<?php

$callback = isset($_GET['callback']) ? trim($_GET['callback']) : ''; //jsonp回调参数,必需
//采用jsonp 解决跨域问题 方式处理
if($callback!=''){
$callback = $_GET['callback'];
$date = array('status'=>'1','msg'=>'OK');
echo $callback.'('.json_encode($data).')';
}
else{

//通过header解决跨域问题
header('Content-Type: application/json');
header("Access-Control-Request-Method: *");
header('Access-Control-Allow-Headers:x-requested-with,content-type');
header("Access-Control-Allow-Origin: *");
header('Access-Control-Max-Age: 60');

$uname = isset($_GET['uname']) ? trim($_GET['uname']) : '';

//echo  json_decode($_POST);

$id=isset($_POST['id'])?$_POST['id']: '';
if($uname!=''){
$date = array('uname'=>$uname);
$date["msg"]="get OK";
$date["status"]="1";
echo json_encode($date);
}
if($id!=''){
$date = array('id'=>$id);
$date["msg"]="Post OK";
$date["status"]="1";
echo json_encode($date);
}
//echo json_decode(file_get_contents('php://input'),true);
}

?>


备注:具体原理:http://victorblog.com/2012/12/20/make-angularjs-http-service-behave-like-jquery-ajax/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: