有人能告诉我为什么下面的语句没有将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对象发送吗?
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
我也遇到过类似的问题,我在做类似的事情,但没有成功。我的Spring控制器无法读取数据参数。
var paramsVal={data:'"id":"1"'};
$http.post("Request URL", {params: paramsVal});
但是阅读这个论坛和API文档,我试着按照下面的方法,这对我有用。
如果有人也有类似的问题,你也可以试试下面的方法。
$http({
method: 'POST',
url: "Request URL",
params: paramsVal,
headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'}
});
请查看https://docs.angularjs.org/api/ng/service/$http#post了解param config的功能。
{data:'"id":"1"'} -字符串或对象的映射将被转换为URL?数据= " id: 1”
与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将不起作用!
希望这个方法对我有用,对你也有用。