有人能告诉我为什么下面的语句没有将post数据发送到指定的url吗?url被调用,但在服务器上,当我打印$_POST -我得到一个空数组。如果我在控制台中打印消息,然后将其添加到数据-它显示了正确的内容。

$http.post('request-url',  { 'message' : message });

我也尝试过将数据作为字符串(具有相同的结果):

$http.post('request-url',  "message=" + message);

当我以以下格式使用它时,它似乎正在工作:

$http({
    method: 'POST',
    url: 'request-url',
    data: "message=" + message,
    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
});

但是是否有一种方法可以用$http.post() -我总是必须包括头以便它工作吗?我相信上面的内容类型是指定发送数据的格式,但我可以把它作为javascript对象发送吗?


当前回答

当我遇到这个问题时,我发布的参数原来是一个对象数组,而不是一个简单的对象。

其他回答

上面不是很清楚,但如果你用PHP接收请求,你可以使用:

$params = json_decode(file_get_contents('php://input'),true);

从AngularJS POST中访问PHP中的数组。

这个问题最终在angular 1.4中使用$httpParamSerializerJQLike解决了

参见https://github.com/angular/angular.js/issues/6039

.controller('myCtrl', function($http, $httpParamSerializerJQLike) {
$http({
  method: 'POST',
  url: baseUrl,
  data: $httpParamSerializerJQLike({
    "user":{
      "email":"wahxxx@gmail.com",
      "password":"123456"
    }
  }),
  headers:
    'Content-Type': 'application/x-www-form-urlencoded'
})})

It's not angular's fault. Angular is designed to work in JSON world. So when $http service send AJAX request, it send all your data as a payload, not as form-data so that your backend application can handle it. But jQuery does some things internally. You instruct jQuery's $ajax module to bind form-data as JSON but before sending AJAX request, it serialized JSON and add application/x-www-form-urlencoded header. This way your backend application able to received form-data in form of post parameters and not JSON.

但是你可以修改angular $http服务的默认行为

添加标题 序列化json

$httpParamSerializerJQLike是angular的内置服务,它以同样的方式序列化json。jQuery的参数。

$http({
    method: 'POST',
    url: 'request-url',
    data: $httpParamSerializerJQLike(json-form-data),
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8;'
    }
});

如果你需要一个插件先将表单数据序列化成JSON,可以使用这个插件https://github.com/marioizquierdo/jquery.serializeJSON

与JQuery不同,出于学究的考虑,Angular使用JSON格式进行POST 数据从客户端传输到服务器端(JQuery应用x-www-form-urlencoded,尽管JQuery和Angular使用JSON进行数据输入)。因此有两个部分的问题:在js客户端部分和在你的服务器部分。所以你需要:

把js的Angular客户端部分像这样放: http({美元 方法:“文章”, url:“请求url”, data: {'message': 'Hello world'} });

AND

写入服务器部分以接收来自客户端的数据(如果是php)。 $data = file_get_contents("php://input"); $ datasondecode = json_decode($data); $message = $dataJsonDecode->消息; echo $消息;/ /“Hello world”

注意:$_POST将不起作用!

希望这个方法对我有用,对你也有用。

我写了一个小的PHP帮助函数,允许这两种类型的输入参数:

function getArgs () {
    if ($input = file_get_contents('php://input') && $input_params = json_decode($input,true))
        return $input_params + $_POST + $_GET;
    return $_POST + $_GET;
}

用法:

<?php
    include("util.php"); # above code
    $request = getArgs();

    $myVar = "";
    if (isset($request['myVar']))
        $myVar = $request['myVar'];
?>

因此不需要修改JavaScript。