繁体   English   中英

AngularJS HTTP发布到PHP并且未定义

[英]AngularJS HTTP post to PHP and undefined

我有一个带有标签ng-submit="login()的表单

该函数在javascript中被称为fine。

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');
        });
    }
}

我从PHP文件中得到200 OK响应,但是,返回的数据表明emailpassword未定义。 这是我的所有PHP

<?php
$email = $_POST['email'];
$pass  = $_POST['password'];
echo $email;
?>

知道为什么我得到未定义的POST值吗?

编辑

我想指出,因为这似乎是一个受欢迎的问题(但它已经过时了), .success.error已被弃用,你应该使用.then .then因为@James Gentes在提交中指出

angularjs .post()默认Content-type标头为application/json 您将覆盖此项以传递表单编码数据,但是您不会更改data值以传递适当的查询字符串,因此PHP不会按预期填充$_POST

我的建议是只使用application/json的默认angularjs设置作为标头,在PHP中读取原始输入,然后反序列化JSON。

这可以通过PHP实现,如下所示:

$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$email = $request->email;
$pass = $request->password;

或者,如果您严重依赖$_POST功能,则可以形成一个查询字符串,如email=someemail@email.com&password=somepassword ,并将其作为数据发送。 确保此查询字符串是URL编码的。 如果手动构建(而不是使用像jQuery.serialize()这样的东西),Javascript的encodeURIComponent()应该为你做。

我在服务器端这样做,在我的init文件的开头,就像一个魅力,你不需要在角度或现有的PHP代码中做任何事情:

if ($_SERVER['REQUEST_METHOD'] == 'POST' && empty($_POST))
    $_POST = json_decode(file_get_contents('php://input'), true);

在我正在开发的API中,我有一个基本控制器,在其__construct()方法中,我有以下内容:

if(isset($_SERVER["CONTENT_TYPE"]) && strpos($_SERVER["CONTENT_TYPE"], "application/json") !== false) {
    $_POST = array_merge($_POST, (array) json_decode(trim(file_get_contents('php://input')), true));
}

这允许我在需要时简单地将json数据引用为$ _POST [“var”]。 效果很好。

这样一来,如果经过身份验证的用户连接了一个库,这样的jQuery发送的帖子数据默认为Content-Type:application / x-www-form-urlencoded或Content-Type:application / json,那么API将会毫无错误地响应使API更适合开发人员。

希望这可以帮助。

因为PHP本身不接受JSON'application 'application/json'一种方法是从angular更新标题和参数,以便api可以直接使用数据。

首先 ,参数化您的数据:

data: $.param({ "foo": $scope.fooValue })

然后 ,将以下内容添加到$http

 headers: {
     'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'
 }, 

如果您的所有请求都转到PHP,则可以在配置中将参数设置为全局,如下所示:

myApp.config(function($httpProvider) {
    $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
});

Angular Js演示代码: -

angular.module('ModuleName',[]).controller('main', ['$http', function($http){

                var formData = { password: 'test pwd', email : 'test email' };
                var postData = 'myData='+JSON.stringify(formData);
                $http({
                        method : 'POST',
                        url : 'resources/curl.php',
                        data: postData,
                        headers : {'Content-Type': 'application/x-www-form-urlencoded'}  

                }).success(function(res){
                        console.log(res);
                }).error(function(error){
                        console.log(error);
        });

        }]);

服务器端代码: -

<?php


// it will print whole json string, which you access after json_decocde in php
$myData = json_decode($_POST['myData']);
print_r($myData);

?>

由于角度行为,在PHP服务器上没有直接的方法用于正常的帖子行为,所以你必须在json对象中管理它。

在将表单数据作为第二个参数传递给.post()之前,需要反序列化表单数据。 您可以使用jQuery的$ .param(data)方法实现此目的。 然后,您将能够在服务器端引用它,如$ .POST ['email'];

这是最好的解决方案(IMO),因为它不需要jQuery,也不需要JSON解码:

资料来源: https//wordpress.stackexchange.com/a/179373和: https//stackoverflow.com/a/1714899/196507

摘要:

//Replacement of jQuery.param
var serialize = function(obj, prefix) {
  var str = [];
  for(var p in obj) {
    if (obj.hasOwnProperty(p)) {
      var k = prefix ? prefix + "[" + p + "]" : p, v = obj[p];
      str.push(typeof v == "object" ?
        serialize(v, k) :
        encodeURIComponent(k) + "=" + encodeURIComponent(v));
    }
  }
  return str.join("&");
};

//Your AngularJS application:
var app = angular.module('foo', []);

app.config(function ($httpProvider) {
    // send all requests payload as query string
    $httpProvider.defaults.transformRequest = function(data){
        if (data === undefined) {
            return data;
        }
        return serialize(data);
    };

    // set all post requests content type
    $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
});

例:

...
   var data = { id: 'some_id', name : 'some_name' };
   $http.post(my_php_url,data).success(function(data){
        // It works!
   }).error(function() {
        // :(
   });

PHP代码:

<?php
    $id = $_POST["id"];
?>

这是一个老问题,但值得一提的是,在Angular 1.4中添加了httpParamSerializer,当使用$ http.post时,如果我们使用$ httpParamSerializer(params)传递参数,一切都像常规的post请求一样,没有JSON反序列化是在服务器端需要。

https://docs.angularjs.org/api/ng/service/$httpParamSerializer

在使用Angular和PHP时,花了我几个小时的时间来理解它。 发布数据不会在$ _POST中转到PHP

在PHP代码中执行以下操作。 - 创建一个变量$ angular_post_params - 然后执行以下$angular_http_params = (array)json_decode(trim(file_get_contents('php://input')));

现在,您可以像$ _POST一样访问您的参数

$angular_http_params["key"]

万一你想知道javascript ....这是我用过的

    var myApp = angular.module('appUsers', []);
    //var post_params = $.param({ request_type: "getListOfUsersWithRolesInfo" });
    var dataObj = {
        task_to_perform: 'getListOfUsersWithRolesInfo'
    };

    myApp.controller('ctrlListOfUsers', function ($scope, $http) {
        $http({
            method: 'POST',
            dataType: 'json',
            url: ajax_processor_url,
            headers: {
                'Content-Type': 'application/json'
            },
            data: dataObj,
            //transformRequest: function(){},
            timeout: 30000,
            cache: false
        }).
        success(function (rsp) {
            console.log("success");
            console.log(rsp);
        }).
        error(function (rsp) {
            console.log("error");
        });
    });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM