AngularJS HTTP 发布到 PHP 并且未定义

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15485354/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 09:19:19  来源:igfitidea点击:

AngularJS HTTP post to PHP and undefined

phpjavascriptangularjs

提问by Ronnie

I have a form with the tag ng-submit="login()

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

The function gets called fine in javascript.

该函数在 javascript 中被调用得很好。

function LoginForm($scope, $http)
{
    $http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';

    $scope.email    = "[email protected]";
    $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');
        });
    }
}

I am getting a 200 OK response back from the PHP file, however, the returned data is saying that emailand passwordare undefined. This is all the php I have

我从 PHP 文件中得到 200 OK 响应,但是,返回的数据是这样说的,email并且password是未定义的。这是我所有的 php

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

Any idea why I am getting undefined POSTvalues?

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

EDIT

编辑

I wanted to point out since this seems to be a popular question (yet it is old), .successand .errorhave been deprecated and you should use .thenas @James Gentes pointed out in the commments

我想指出,因为这似乎是一个受欢迎的问题(但它已经过时).success并且.error已被弃用,您应该.then像@James Gentes 在评论中指出的那样使用

回答by Mike Brant

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 datavalue to pass an appropriate query string, so PHP is not populating $_POSTas you expect.

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

My suggestion would be to just use the default angularjs setting of application/jsonas header, read the raw input in PHP, and then deserialize the JSON.

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

That can be achieved in PHP like this:

这可以在 PHP 中实现,如下所示:

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

Alternately, if you are heavily relying on $_POSTfunctionality, you can form a query string like [email protected]&password=somepasswordand 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.

或者,如果您严重依赖$_POST功能,您可以形成一个查询字符串[email protected]&password=somepassword,并将其作为数据发送。确保此查询字符串是 URL 编码的。如果手动构建(而不是使用类似的东西jQuery.serialize()),JavascriptencodeURIComponent()应该为您解决问题。

回答by valmarv

I do it on the server side, at the begining of my init file, works like a charm and you don't have to do anything in angular or existing php code:

我在服务器端做这件事,在我的 init 文件的开头,就像一个魅力,你不必在 angular 或现有的 php 代码中做任何事情:

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

回答by Tim Wickstrom

In the API I am developing I have a base controller and inside its __construct() method I have the following:

在我正在开发的 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));
}

This allows me to simply reference the json data as $_POST["var"] when needed. Works great.

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

That way if an authenticated user connects with a library such a jQuery that sends post data with a default of Content-Type: application/x-www-form-urlencoded or Content-Type: application/json the API will respond without error and will make the API a little more developer friendly.

这样,如果经过身份验证的用户连接到一个库,例如 jQuery,它发送默认为 Content-Type: application/x-www-form-urlencoded 或 Content-Type: application/json 的发布数据,API 将无错误地响应,并且使 API 对开发人员更加友好。

Hope this helps.

希望这可以帮助。

回答by Malkus

Because PHP does not natively accept JSON 'application/json'One approach is to update your headers and parameters from angular so that your api can use the data directly.

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

First, Parameterize your data:

首先,参数化你的数据:

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

Then, add the following to your $http

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

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

If all of your requests are going to PHP the parameters can be set globaly in the configuration as follows:

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

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

回答by Rajendra Khabiya

Angular Js Demo Code :-

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

        }]);

Server Side Code :-

服务器端代码:-

<?php


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

?>

Due to angular behaviour there is no direct method for normal post behaviour at PHP server, so you have to manage it in json objects.

由于角度行为,在 PHP 服务器上没有针对正常发布行为的直接方法,因此您必须在 json 对象中对其进行管理。

回答by lepe

This is the best solution (IMO) as it requires no jQuery and no JSON decode:

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

Source: https://wordpress.stackexchange.com/a/179373and: https://stackoverflow.com/a/1714899/196507

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

Summary:

概括:

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

Example:

例子:

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

PHP code:

PHP代码:

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

回答by bahramzy

You need to deserialize your form data before passing it as the second parameter to .post (). You can achieve this using jQuery's $.param (data) method. Then you will be able to on server side to reference it like $.POST ['email'];

在将表单数据作为第二个参数传递给 .post() 之前,您需要对其进行反序列化。您可以使用 jQuery 的 $.param (data) 方法来实现这一点。然后你就可以在服务器端像 $.POST ['email']; 一样引用它。

回答by Sep

It's an old question but it worth to mention that in Angular 1.4 $httpParamSerializer is added and when using $http.post, if we use $httpParamSerializer(params) to pass the parameters, everything works like a regular post request and no JSON deserializing is needed on server side.

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

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

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

回答by Talha

It took me hours to understand that while working with Angular and PHP. Post data was not going to PHP in $_POST

在使用 Angular 和 PHP 时,我花了几个小时才理解这一点。发布数据不会在 $_POST 中发送到 PHP

in PHP code do the following. - Create a variable $angular_post_params - Then do the following $angular_http_params = (array)json_decode(trim(file_get_contents('php://input')));

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

now you can access your parameters like you do from $_POST

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

$angular_http_params["key"]

$angular_http_params["key"]

in case you were wondering about javascript....this is what i used

如果你想知道 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");
        });
    });