这是我第一次使用 AngulerJS。我正在尝试将数据POST
到服务器。
AngularJS 代码
var app = angular.module("myApp", []);
var BASE_URL = "http://localhost/project/api/Data/";
var GET_DATA = BASE_URL+"get_data";
console.log(GET_DATA);
app.controller('myCtrl', function($scope, $http) {
var inputs = { "user_id": "3"};
var config = {
headers : {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
}
}
$http.post(GET_DATA , inputs, config)
.success(function (response, status, headers, config) {
$scope.content = response.error;
$scope.statuscode = response.status;
$scope.statustext = response.statusInfo;
console.log(response);
})
.error(function (data, status, header, config) {
$scope.ResponseDetails = "Data: " + data +
"<hr />status: " + status +
"<hr />headers: " + header +
"<hr />config: " + config;
});
});
此代码将数据发送到服务器,但采用某种有线格式。以下是我的 print_r($_POST);
结果:
Array
(
[{"user_id":"3"}] =>
[0] =>
)
这是错误的结果,我期待类似的结果
Array
(
user_id => 3
)
注意:我在服务器端使用 CodeIgniter 框架。
最佳答案
您可以以 json
格式发送帖子数据:
$http.post(GET_DATA , {"user_id": "3"})
.success(function (response, status, headers, config) {
$scope.content = response.error;
$scope.statuscode = response.status;
$scope.statustext = response.statusInfo;
console.log(response);
})
.error(function (data, status, header, config) {
$scope.ResponseDetails = "Data: " + data +
"<hr />status: " + status +
"<hr />headers: " + header +
"<hr />config: " + config;
});
});
在服务器端,您可以获取如下的发布数据:
$postdata = json_decode(file_get_contents('php://input'));
print_r($postdata);
当请求内容类型为 application/x-www-form-urlencoded` 时,您必须以 urlencoded
格式对帖子正文中的数据进行编码。应该是这样的:
var inputs = 'student_id=3';
关于php - 无法使用 AngularJS post 方法获取正确的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36232651/