我使用angular将数据发布到PHP JSON webservice但无法正确获取
这是我的.http方法代码
app.controller('AddCustomer',['$http','$scope',function($http,$scope){
$scope.freshRequest = true;
$scope.addCustomer=function(){
var data_to_send={};
data_to_send.name=$scope.name;
alert(data_to_send.name);
$http({
method: 'POST',
url: '../service/add_new_Customer.php',
data: data_to_send,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function(returnedData){
$scope.freshRequest = false;
$scope.response = returnedData.response;
$scope.accountNumber= returnedData.accountNumber;
$scope.updatedBalance= returnedData.updatedBalance;
$scope.transactionSuccessful = returnedData.transactionSuccessful;
}).error(function (data, status, headers, config) {
$scope.status = status + ' ' + headers;
console.log($scope.status)});
};}]);
下面是我用来调用addCustomer()方法的htm表单
<form class="form-horizontal" novalidate ng-controller="AddCustomer as add" ng-submit="addCustomer()">
<input id="name" name="name" type="text" placeholder="" class="form-control input-md" required="" ng-model="name">
<input id="fname" name="fname" type="text" placeholder="" class="form-control input-md" required="" ng-model="fname">
<button id="button1id" type="submit" name="button1id" class="btn btn-primary">Add</button>
当我正在执行$ _REQUEST [&#39; name&#39;]或$ _POST [&#39; name&#39;]时,我的php为字段名称变为null;
下面是php代码
<?php
class Summary{
public $response= "Account Could not be added invalid data";
public $transactionSuccessful= "";
public $updatedBalance= "";
public $accountNumber= "";
}
$e = new Summary();
$final_res =json_encode($jsonObj) ;
if( $_REQUEST['name'] ){
$e->response = $_REQUEST['name'];
}
else{
$e->response = "Account Could not be added invalid data";
}
$e->transactionSuccessful= true;
$e->updatedBalance= $_POST['name'];
$e->accountNumber= $_POST['name'];
echo json_encode($e);
答案 0 :(得分:3)
首先,您需要将发布的数据解码为json,然后才能访问该对象的属性。 file_get_contents("php://input")
允许您阅读原始发布的数据。这就是你如何得名。
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
@$name = $request->name;