AngularJs $http.post() does not send data

前端 未结 30 1754
我在风中等你
我在风中等你 2020-11-22 02:51

Could anyone tell me why the following statement does not send the post data to the designated url? The url is called but on the server when I print $_POST - I get an empty

相关标签:
30条回答
  • 2020-11-22 03:37

    This has finally been addressed in angular 1.4 using $httpParamSerializerJQLike

    See https://github.com/angular/angular.js/issues/6039

    .controller('myCtrl', function($http, $httpParamSerializerJQLike) {
    $http({
      method: 'POST',
      url: baseUrl,
      data: $httpParamSerializerJQLike({
        "user":{
          "email":"wahxxx@gmail.com",
          "password":"123456"
        }
      }),
      headers:
        'Content-Type': 'application/x-www-form-urlencoded'
    })})
    
    0 讨论(0)
  • 2020-11-22 03:37

    I know has accepted answer. But, following might help to future readers, if the answer doesn't suit them for any reason.

    Angular doesn't do ajax same as jQuery. While I tried to follow the guide to modify angular $httpprovider , I encountered other problems. E.g. I use codeigniter in which $this->input->is_ajax_request() function always failed (which was written by another programmer and used globally, so cant change) saying this was not real ajax request.

    To solve it, I took help of deferred promise. I tested it in Firefox, and ie9 and it worked.

    I have following function defined outside any of the angular code. This function makes regular jquery ajax call and returns deferred/promise (I'm still learning) object.

    function getjQueryAjax(url, obj){
        return $.ajax({
            type: 'post',
            url: url,
            cache: true,
            data: obj
        });
    }
    

    Then I'm calling it angular code using the following code. Please note that we have to update the $scope manually using $scope.$apply() .

        var data = {
            media: "video",
            scope: "movies"
        };
        var rPromise = getjQueryAjax("myController/getMeTypes" , data);
        rPromise.success(function(response){
            console.log(response);
            $scope.$apply(function(){
                $scope.testData = JSON.parse(response);
                console.log($scope.testData);
            });
        }).error(function(){
            console.log("AJAX failed!");
        });
    

    This may not be the perfect answer, but it allowed me to use jquery ajax calls with angular and allowed me to update the $scope.

    0 讨论(0)
  • 2020-11-22 03:38

    Unlike JQuery and for the sake of pedantry, Angular uses JSON format for POST data transfer from a client to the server (JQuery applies x-www-form-urlencoded presumably, although JQuery and Angular uses JSON for data imput). Therefore there are two parts of problem: in js client part and in your server part. So you need:

    1. put js Angular client part like this:

      $http({
      method: 'POST',
      url: 'request-url',
      data: {'message': 'Hello world'}
      });
      

    AND

    1. write in your server part to receive data from a client (if it is php).

              $data               = file_get_contents("php://input");
              $dataJsonDecode     = json_decode($data);
              $message            = $dataJsonDecode->message;
              echo $message;     //'Hello world'
      

    Note: $_POST will not work!

    The solution works for me fine, hopefully, and for you.

    0 讨论(0)
  • 2020-11-22 03:39

    Just put the data you want to send as second parameter:

    $http.post('request-url',  message);
    

    Another form which also works is:

    $http.post('request-url',  { params: { paramName: value } });
    

    Make sure that paramName exactly matches the name of the parameter of the function you are calling.

    Source: AngularJS post shortcut method

    0 讨论(0)
  • 2020-11-22 03:40

    I use jQuery param with AngularJS post requrest. Here is a example ... create AngularJS application module, where myapp is defined with ng-app in your HTML code.

    var app = angular.module('myapp', []);
    

    Now let us create a Login controller and POST email and password.

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

    I don't like to exaplain the code, it is simple enough to understand :) Note that param is from jQuery, so you must install both jQuery and AngularJS to make it working. Here is a screenshot.

    enter image description here

    Hope this is helpful. Thanks!

    0 讨论(0)
  • 2020-11-22 03:45

    I don't have the reputation to comment, but in response/addition to Don F's answer:

    $params = json_decode(file_get_contents('php://input'));

    A second parameter of true needs to be added to the json_decode function in order to properly return an associative array:

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

    0 讨论(0)
提交回复
热议问题