有人能告诉我为什么下面的语句没有将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对象发送吗?
我使用jQuery参数与AngularJS post请求。这里有一个例子……创建AngularJS应用模块,其中myapp在HTML代码中用ng-app定义。
var app = angular.module('myapp', []);
现在让我们创建一个登录控制器和POST电子邮件和密码。
app.controller('LoginController', ['$scope', '$http', function ($scope, $http) {
// default post header
$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
// send login data
$http({
method: 'POST',
url: 'https://example.com/user/login',
data: $.param({
email: $scope.email,
password: $scope.password
}),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function (data, status, headers, config) {
// handle success things
}).error(function (data, status, headers, config) {
// handle error things
});
}]);
我不喜欢解释代码,它足够简单易懂:)注意,param来自jQuery,所以你必须同时安装jQuery和AngularJS才能使它工作。这是一个截图。
希望这对你有帮助。谢谢!
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