我有一个发送到我的 php 文件的 Angular 帖子,但在 PHP 文件中,我无法从 post 变量访问任何内容。它返回我的 SUCCESS 字符串,但之后什么也没有,所以我在帖子上的返回是“SUCCESS - - - - -”,其中数据应该在破折号之间。
JSON/JS 对象:
DESCRIPTION: "123321"
LOCATION: "ab_calgary_eighth_ave_pl"
NAME: "123321"
QUANTITY: 123321
TYPE: "cycle"
Angular POST 代码:
$scope.insertNewInventoryItem = function()
{
if(typeof ($scope.newItem.LOCATION) == 'undefined')
alert("LocationCannot Be Empty. Please Select An Option From The Drop Down.");
else if(typeof ($scope.newItem.TYPE) == 'undefined')
alert("Type Cannot Be Empty. Please Select An Option From The Drop Down.");
else
{
$http.post("dataaccess/addnewinventory.php", $scope.newItem).then(onAddNewComplete, onAddNewError);
}
}
PHP 页面试图查找发布的值:
<?php
$con = mysqli_connect("localhost", "dbadminuser", "password", "database_demo_inventory");
// Check connection
if (mysqli_connect_errno())
{
echo "FAIL - Failed to connect to MySQL: " . mysqli_connect_error();
}
else
{
echo "SUCCESS - " . $HTTP_POST_VARS['newItem.NAME'] . " - " . $HTTP_POST_VARS['TYPE'] . " - " . $HTTP_POST_VARS["QUANTITY"] . " - " . $HTTP_POST_VARS . " - " . $_POST[0];
}
mysqli_close($con);
?>
来自 GOOGLE 开发者工具的请求图片:
请求返回数据的图片(有关 SUCCESS 的来源,请参阅 PHP 代码):
为什么我不能访问帖子变量?我在这里遗漏了什么吗?
最佳答案
默认情况下,Angular 使用 Content-Type: "application/json"传输数据,而 PHP 本身无法将 JSON 数据解析为 $_POST。您可以按照以下两个步骤来解决此问题:
第 1 步:更改 header Content-Type 的默认值:
angular.module("myApp",[], function($httpProvider){
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
})
第 2 步:将 JSON 数据转换为 key=value 对序列化数据。 (我正在使用 jQuery $.param 函数来转换数据)
$http({
method:"POST",
url: "post.php",
data: $.param($scope.newItem)
}).success(function(data, status, headers, config){
console.log(data);
}).error(function(data, status, headers, config){
console.log(status);
});
注意:$HTTP_POST_VARS 不是 super 全局变量,它在 PHP 5 中已完全弃用。我认为您可以使用 $_POST。
关于javascript - 为什么我对 PHP 页面的 Angular POST 请求没有设置 POST 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24602203/