Angular $http帖子没有正确发布 PHP 的变量


Angular $http post not posting variable correctly for PHP

我的应用程序中有一个PHP服务api/add,你可以通过POST rqname传递它。 rq告诉服务要执行什么功能,因此在我的示例中定义了addCity,它将一个城市插入到数据库中,name是城市的名称。

所以,话

虽如此,这是我的角度代码。我正在用ngRoute定义上面的角度模块。

whereApp.controller('AddCityCtrl', function($scope, $http) {
  $scope.addCity = function() {
    $http({
        method: "POST",
        url: '/api/add/',
        data: { rq:'addCity', name: $scope.name },
        headers: {'Content-Type': 'application/x-www-form-urlencoded'}
        }).success(function (data, status, headers, config) {
            console.log(data); 
        });
    /*
        $.ajax({
            url: "/api/add/",
            type: "POST",
            data: { rq: 'addCity', name: $scope.name },
            dataType: "json"
        })
        .success(function(data) {
            console.log(data);    
        });
    */
  }
});

问题来了。ajax 请求(被注释掉的 jQuery 样式(有效。我想使用棱角分明的风格,因为,嗯,这是我正在使用的,也是我试图更多地学习的东西。jQuery ajax 调用为我提供了来自服务器端的成功消息,$http 方法说未定义rq变量,我正在通过 $_POST['rq'] 访问该变量。

我已经在谷歌上做了一些研究,但到目前为止,我只提出了像这篇文章所说的那样添加headers: {'Content-Type': 'application/x-www-form-urlencoded'}

谁能告诉我这两个 ajax 调用之间有什么区别(或者是否有其他我没有考虑过的东西(?

由于它是用 php 发送的 json 数据,因此您无法通过简单的 $_POST 来获取它,您需要做这种事情来获取此发布的数据

$data=file_get_contents('php://input');
$dataobj= json_decode($data);

在这里,您首先获取数据,然后将其从json解码为普通对象