AngularJS HTTP发布到PHP [英] AngularJS HTTP Post to PHP

查看:84
本文介绍了AngularJS HTTP发布到PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用$http方法将某些数据从angularjs控制器发布到php页面.

I am posting some data to a php page from angularjs controller using the $http method as shown below.

$scope.login = function(){
    var data = {
        'username' : $scope.username,
        'password' : $scope.password
    };
    $http.post('login.php', data).success(function(response){
        console.log(response);
    });
};

我知道我可以使用<

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

但是我想知道angularjs中是否有更好的方法,因此我可以在php中使用简单的$_POST来检索数据.

But I was wondering if there is better way in angularjs so I could use the simple $_POST in php to retrieve the data.

jQuery中,我们可以简单地使用$.post,而这些在$_POST中可用于php.为什么angularjs并不是那么简单. 在angularjs中执行$http post请求时,有什么方法可以填充php$_POST.请帮忙.

In jQuery we could just simply use $.post and those are available for php in $_POST. Why for angularjs that is not that simple. Is there any way to populate $_POST of php when we do a $http post request in angularjs. Please help.

推荐答案

您需要将请求转换为php known格式.
我使用jQuery $.param方法进行构建.您可以编写自己的.

You need to convert your request to php known format.
I use jQuery $.param method to build it. You can write your own.

app.config(['$httpProvider', function($http) {  
    $http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
    $http.defaults.transformRequest = function(data) {
            return $.param(data);
        };
    }]);


urlencoded遵循简单格式:


urlencoded is followed simple format:

username=Name&password=My%20Password


JSFiddle

这篇关于AngularJS HTTP发布到PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆