角HTTP发布到PHP和undefined [英] Angular HTTP post to PHP and undefined
问题描述
我有标记形式NG提交=登录()
该函数被调用javascript中的罚款。
The function gets called fine in javascript.
function LoginForm($scope, $http)
{
$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
$scope.email = "fsdg@sdf.com";
$scope.password = "1234";
$scope.login = function()
{
data = {
'email' : $scope.email,
'password' : $scope.password
};
$http.post('resources/curl.php', data)
.success(function(data, status, headers, config)
{
console.log(status + ' - ' + data);
})
.error(function(data, status, headers, config)
{
console.log('error');
});
}
}
我得到一个200 OK响应从PHP回文件,然而,返回的数据是说,电子邮件
和密码
是不确定的。这是所有的PHP我有
I am getting a 200 OK response back from the PHP file, however, the returned data is saying that email
and password
are undefined. This is all the php I have
<?php
$email = $_POST['email'];
$pass = $_POST['password'];
echo $email;
?>
任何想法,为什么我收到未定义 POST
值?
修改
我想指出,因为这似乎是一个普遍的问题(但它是旧), .success
和 .error
已去precated,你应该使用。然后
作为@詹姆斯氏族在commments指出
I wanted to point out since this seems to be a popular question (yet it is old), .success
and .error
have been deprecated and you should use .then
as @James Gentes pointed out in the commments
推荐答案
angularjs 。员额()
默认的Content-type头为应用程序/ JSON
。您正在重写此通过形式恩codeD数据,但是你不改变你的数据
值传递适当的查询字符串,因此PHP没有填充 $ _ POST
如您所愿。
angularjs .post()
defaults the Content-type header to application/json
. You are overriding this to pass form-encoded data, however you are not changing your data
value to pass an appropriate query string, so PHP is not populating $_POST
as you expect.
我的建议是只使用应用程序/ JSON
默认angularjs设置为标题,阅读PHP原始输入,然后反序列化JSON。
My suggestion would be to just use the default angularjs setting of application/json
as header, read the raw input in PHP, and then deserialize the JSON.
这可以用PHP来实现这样的:
That can be achieved in PHP like this:
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$email = $request->email;
$pass = $request->password;
另外,如果你是严重依赖于 $ _ POST
功能,可以形成一个查询字符串 email=someemail@email.com&密码= somepassword
和发送数据。请确保此查询字符串URL连接codeD。如果是手动建(而不是使用像 jQuery.serialize()
的东西),JavaScript的连接codeURIComponent()
应该做的伎俩给你。
Alternately, if you are heavily relying on $_POST
functionality, you can form a query string like email=someemail@email.com&password=somepassword
and send that as data. Make sure that this query string is URL encoded. If manually built (as opposed to using something like jQuery.serialize()
), Javascript's encodeURIComponent()
should do the trick for you.
这篇关于角HTTP发布到PHP和undefined的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!